Snap to grid
Dec 8 2013 · Graphics and Rendering
Snapping a point to a grid is one of those seemingly complex tasks, which turns out to be actually quite simple when you approach it.
Given a arbitrary point (x,y) the coordinates it would snap to (sx, sy) on a 12×12 grid is found by:
var sx = Math.round(x / 12.0) * 12.0;
var sy = Math.round(y / 12.0) * 12.0;
Of course, 12 can be changed to anything to allow for a grid with different dimensions.