Detecting mouse position on the canvas
suggest changeThis 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 element. e.clientX and e.clientY are positions relative to the viewport. Subtract the canvas’s left and top (from getBoundingClientRect) to make them relative to the canvas. This matches bitmap pixels only when the canvas display size equals its width and height.
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);
});
Math.round keeps the x,y positions as integers, because the canvas bounding rectangle may not sit on integer coordinates.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents