O'Reilly logo

HTML5 Web Application Development By Example Beginner's guide by J.M. Gustafson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required