如果你想要捕捉到一个 nxm 网格的东西,你会想要添加一个监听器来调用一个捕捉它的函数。您可能想在“dragend”中执行此操作
http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-events-tutorial/
box.on("dragend", function(){
snaptogrid(box);
});
...方形瓷砖的 100x100 网格
function snaptogrid(YourObject){
YourObject.x = Math.floor(YourObject.x/100) * 100 + 50;
YourObject.y = Math.floor(YourObject.y/100) * 100 + 50;
}
例如:如果 YourObject.x = 325,那么您将得到 Math.floor(3.25)*100+50 = 350。左侧和顶部都应为 300,而中心应为 350。
编辑,哎呀错过了部分问题。为了捕捉到其他方块,这就是我要做的:
function snaptoOther(YourSquares, index){
var lastone = YourSquares.length-1;
var maxDist = 125;
var minDist = 75;
var squarelength = 100;
for(var i=0; i<lastone; i++)
{
var checkx = abs(YourSquares[index].x - YourSquares[i].x);
var checky = abs(YourSquares[index].y - YourSquares[i].y);
var multiplyX = Math.round((YourSquares[index].x - YourSquares[i].x)/squarelength);
var multiplyY = Math.round((YourSquares[index].y - YourSquares[i].y)/squarelength);
if(checkx < maxDist && checkx > minDist && i !== index)
{
YourSquares[index].x = YourSquares[i].x + multiplyX*squarelength;
}
if(checky < maxDist && checky > minDist && i !== index)
{
YourSquares[index].y = YourSquares[i].y + multiplyY*squarelength;
}
}
}