This example will show how to get the mouse position relative to the canvas, such that (0,0)
will be the top-left hand corner of the HTML5 Canvas. The e.clientX
and e.clientY
will get the mouse positions relative to the top of the document, to change this to be based on the top of the canvas we subtract the left
and right
positions of the canvas from the client X and Y.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "16px Arial";
canvas.addEventListener("mousemove", function(e) {
var cRect = canvas.getBoundingClientRect(); // Gets CSS pos, and width/height
var canvasX = Math.round(e.clientX - cRect.left); // Subtract the 'left' of the canvas
var canvasY = Math.round(e.clientY - cRect.top); // from the X/Y positions to make
ctx.clearRect(0, 0, canvas.width, canvas.height); // (0,0) the top left of the canvas
ctx.fillText("X: "+canvasX+", Y: "+canvasY, 10, 20);
});
The use of Math.round
is due to ensure the x,y
positions are integers, as the bounding rectangle of the canvas may not have integer positions.