在 JavaScript 中对齐网格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6593447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:12:49  来源:igfitidea点击:

Snapping to grid in JavaScript

javascriptgrid

提问by Steve

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

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

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.

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

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

Many thanks

非常感谢

回答by fulmicoton

Have you consider using jquery UI? The draggable utilityallows snapping.

您是否考虑过使用 jquery UI?可拖动实用程序允许捕捉。

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

如果你真的需要实现它,当你不应该捕捉时,这将返回 null。

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