最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Snapping to grid in JavaScript - Stack Overflow

programmeradmin5浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 15

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;
    }
};
发布评论

评论列表(0)

  1. 暂无评论