Snap a Rectangle to a Grid
In this example, we use the
Math.round()
function to snap a rectangle to a grid.
We are registering an anonymous function to listen for
mousemove
events on the canvas. If the mouse is moved over the canvas, a
mousemove
event is generated and passed into the anonymous function, where it is then
stored in the parameter
e
.
canvas.addEventListener('mousemove', function(e) {
// Code block
});
As the mouse moves over the canvas, we can access the mouse's coordinates on
the canvas through the
mousemove
event's
layerX
and
layerY
properties. By setting the width of the rectangle to the value of
layerX
and the height to the value of
layerY
,
we can resize the rectangle so it's bottom left corner moves with the mouse.
However, we don't want the size of the rectangle to change freely as the mouse
moves. We want the rectangle to snap to the grid below.
The lines on the grid are 40 pixels apart. So, to keep the rectangle aligned
to the grid, the dimensions of the rectangle must be multiples of 40. We are
using the
Math.round()
function to round the width and height of the rectangle to the nearest multiple of 40:
canvas.addEventListener('mousemove', function(e) {
var w = 40 * Math.round(e.layerX / 40);
var h = 40 * Math.round(e.layerY / 40);
});
Let's say the mouse's coordinates on the canvas are (190, 85). If we divide 190 by 40
and round the answer, we get 5. This means 40 goes into 190 about 5 times. Multiplying 40
by 5 then gives us 200, a multiple of 40, for the width of the rectangle. If we divide 85
by 40 and round the answer, we get 2. This means 40 goes into 85 about 2 times. Multiplying
40 by 2 then gives us 80, another multiple of 40, for the height of the rectangle. Because
the dimensions of the rectangle are multiples of 40, it snaps to the grid below.
To learn more about handling events, visit the
addEventListener()
lesson.
Quick Reference:
Coordinates
Variables
Functions
fillRect()
save() / restore()
lineTo()