Snap to grid with KonvaJS

Pierre Bernard Le Roux
2 min readSep 16, 2017

--

KonvaJS is a great for drawing anything to the canvas! Recently, I wanted to do something which felt basic but made me think a bit. That is have some rectangle or element automatically snap into a position somewhere on a grid while dragging the element around.

Having this functionality would make organizing elements much easier and quicker. Specifically on an interface where you are moving elements around.

Unfortunately there is no quick tutorial or little script available on the internet, so I made one for you. See the CodePen.io example below for the final result and then scroll further to see how this is accomplished.

Snap to Grid

The idea behind the snap-to-grid part is to change the x, y coordinates of the rectangle to the grid block closest to it. Say for example you have a grid corner at position 10, 10 and a next one at 20, 10 if the x coordinate of the rectangle is between 10 and 15 then you want it to move to 10 as soon as you let it go. Similarly if the x coordinate is between 15 and 20 .

This can be accomplished by taking the coordinate (say 14 ), dividing it by the block size 16 / 10 in the grid, rounding it Math.round(1.6) = 2and then multiplying it again by the block size 1 * 10 = 20. Thereby getting rid of the in between values.

This produces the following code:

rectangle.on(‘dragend’, (e) => {
rectangle.position({
x: Math.round(rectangle.x() / blockSize) * blockSize,
y: Math.round(rectangle.y() / blockSize) * blockSize
});
stage.batchDraw();
});

And that is it. So now when the rectangle is dropped after being dragged it will automatically align nicely with other rectangles.

--

--