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();
Now we add a getCanvasPoint()
method. It takes the pageX
and pageY
parameters, subtracts the canvas element offsets, and returns a new object with x
and y
fields to hold the adjusted coordinates:
this.getCanvasPoint = function(pageX,...