在JavaScript中捕捉到网格

Ste*_*eve 2 javascript grid

我正在寻找一个javascript函数,它使用均匀间隔的网格计算对齐网格值.

现在我有以下代码,它可以作为基本解决方案正常工作,但现在我需要它才能在捕捉位置的2px内进行捕捉,例如使用30px间隔网格和2px限制,它会在0px和2px之间捕捉, 28px和32px,58px和62px等

snapToGrip = function(val,gridSize){
    return gridSize * Math.round(val/gridSize);
};
Run Code Online (Sandbox Code Playgroud)

非常感谢

ful*_*ton 9

你考虑过使用jquery UI吗?可拖动的实用程序允许捕捉.

如果您确实需要实现它,则在不应该捕捉时返回null.

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

要双方拍摄:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)