previousnext

To get mouse coordinates to work on canvas we need to understand the page geometry. Mouse events belong to the "page" and not to any individual element. Therefore, mouse coordinates are defined with respect to (top left corner of) the page. These coordinates are usually denoted by pageX and pageY.

Each element, such as a canvas, has a position relative to the page. These are known as the left and top offsets (i.e. offsetLeft, offsetTop). Once we know these offsets, we can compute the X and Y coordinates within an element as

X = pageX - offsetLeft;
Y = pageY - offsetTop;

Try running the hidden code and move your mouse cursor within the canvas. Please, make sure that you move it within the "fake canvas" - what this is will become clear when you run the code. You will see a simulation of the above explanation where I have set things up to make the normal cursor disappear inside the fake canvas.

Once you will have done this,we will be ready to go back to our game, and incorporate mouse control.

previousnext