Detecting mouse position on the canvas

suggest change

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 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);
});

Runnable Example

Math.round keeps the x,y positions as integers, because the canvas bounding rectangle may not sit on integer coordinates.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents