3

I'm looking for a javascript function that calculates a snap to grid value using a uniformly spaced grid.

Now I have the following code, which works fine as a basic solution, but now I need it to snap only when within say 2px of the snap position e.g. using a 30px spaced grid and a 2px limit, it would snap between 0px and 2px, 28px and 32px, 58px and 62px, etc.

snapToGrip = function(val,gridSize){
    return gridSize * Math.round(val/gridSize);
};

Many thanks

Yvonne Aburrow
  • 2,602
  • 1
  • 17
  • 47
Steve
  • 3,483
  • 5
  • 21
  • 20

1 Answers1

16

Have you consider using jquery UI? The draggable utility allows snapping.

If you really need to implement it, this returns null when you shouldn't snap.

snapToGrip = function(val,gridSize){
    var snap_candidate = gridSize * Math.floor(val/gridSize);
    if (val-snap_candidate < 2) {
        return snap_candidate;
    }
    else {
        return null;
    }
};

To snap on both side :

snapToGrip = function(val,gridSize){
    var snap_candidate = gridSize * Math.round(val/gridSize);
    if (Math.abs(val-snap_candidate) < 2) {
        return snap_candidate;
    }
    else {
        return null;
    }
};
fulmicoton
  • 15,502
  • 9
  • 54
  • 74
  • 1
    Yes, I considered it, but I'm building a bespoke application that doesn't justify using such a library. – Steve Jul 06 '11 at 08:26
  • Thanks, appreciate it. I've implemented the code, which works fine when moving an object from right to left (snap point) but not when dragging from left to right (snap point). – Steve Jul 06 '11 at 08:42
  • @Steve I don't understand... You said you wanted to snap between 0px and 2px. So you want to do so between -2px and 2px? – fulmicoton Jul 06 '11 at 08:43
  • Sorry for the confusion. Nothing can be dragged beyond the grid - objects are constrained so that they can't be dropped at anything less than 0px. – Steve Jul 06 '11 at 08:49
  • you're a star! The solution you provided works like a treat. Thanks a million poulejapon :) – Steve Jul 06 '11 at 08:50
  • @Steve oh right, sorry I'm the one who didn't read that properly – fulmicoton Jul 06 '11 at 09:20
  • Thanks @poulejapon, I have looked all over and your second snap to grid code snippet is the simplest and best solution. – Rui Marques Jan 11 '13 at 16:35