Time for action – showing the coordinates

The first thing we will implement in our Canvas2D object is a way to convert page coordinates to canvas coordinates. Then we will use that to show the mouse coordinates on the page as the user moves their mouse over the canvas.

The problem with mouse coordinates is that they are always offset from the top left of the web page. To get the canvas coordinates we need to find the offset of the <canvas> element on the page and subtract it from the page coordinates.

First we need a variable named pageOffset to hold the offset of the canvas element. We'll set its value using jQuery's offset() method, which gets the page offset of an element. It returns an object with left and top fields:

var pageOffset = $canvas.offset(); ...

Get HTML5 Web Application Development By Example Beginner's guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.