Getting started
Getting started with html5-canvas
Creating a responsive full page canvas
Detecting mouse position on the canvas
Canvas size and resolution
How to add the Html5 Canvas Element to a webpage
Simple animation with 2D context and requestAnimationFrame
Drawing many translated scaled and rotated images quickly
Image cropping using canvas
The Tained canvas
Off screen canvas
Hello World
An index to Html5 Canvas Capabilities Uses
Rotate
Save canvas to image file
Images
Path syntax
Media types and the canvas
Animation
Collisions and intersections
Paths
Text
Clearing the screen
Navigating along a path
Dragging path shapes images
Shadows
Charts diagrams
Polygons
Transformations
Responsive design
Compositing
Pixel manipulation
Contributors

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

Runnable Example

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.

Feedback about page:

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



Table Of Contents