Snapping to grid in JavaScript

15.3k Views Asked by At

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

1

There are 1 best solutions below

7
On BEST ANSWER

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;
    }
};