Easeljs snap to grid

1.5k views Asked by At

I am building an app using HTML5 in which a grid is drawn. I have some shapes on it that you can move. What I'm trying to do is to snap objects to some points defined when you hover them while moving a shape. What I tried is to save anchors points inside an array and when the shape is dropped, I draw the shape on the closest anchor point. Easeljs is my main js lib so I want to keep it but if needed I can use an other one with easeljs.

Thanks in advance for your help!

1

There are 1 answers

0
Lanny On BEST ANSWER

This is pretty straightforward:

  1. Loop over each point, and get the distance to the mouse
  2. If the item is closer than the others, set the object to its position
  3. Otherwise snap to the mouse instead

Here is a quick sample with the latest EaselJS: http://jsfiddle.net/lannymcnie/qk1gs3xt/

The distance check looks like this:

// Determine the distance from the mouse position to the point
var diffX = Math.abs(event.stageX - p.x);
var diffY = Math.abs(event.stageY - p.y); 
var d = Math.sqrt(diffX*diffX + diffY*diffY);        

// If the current point is closeEnough and the closest (so far)
// Then choose it to snap to.
var closest = (d<snapDistance && (dist == null || d < dist));
if (closest) {
     neighbour = p;          
}

And the snap is super simple:

// If there is a close neighbour, snap to it. 
if (neighbour) {
    s.x = neighbour.x;
    s.y = neighbour.y;

// Otherwise snap to the mouse
} else {
    s.x = event.stageX;
    s.y = event.stageY;
}

Hope that helps!