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
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
Share Improve this question edited Nov 10, 2020 at 16:55 Yvonne Aburrow 2,7281 gold badge21 silver badges49 bronze badges asked Jul 6, 2011 at 8:21 SteveSteve 3,6635 gold badges22 silver badges20 bronze badges1 Answer
Reset to default 15Have 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;
}
};