Ben Shepherd
Ben Shepherd

Reputation: 51

Incorrect mouse coordinates when drawing on Canvas

I'm trying to draw on a canvas, but the mouse positions are off, they seem to be too far to the right when I draw.

The canvas is centered in the middle with a width of 960px.

Here's the URL to the page: http://passion4web.co.uk/ben/canvas/app/

I'm using the following function to get the mouse position:

    function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };  
    }

Upvotes: 1

Views: 1695

Answers (1)

6502
6502

Reputation: 114481

A canvas has two distinct sizes:

  • The size on the page
  • The size in pixel of the image

You need to set the canvas size in pixel to the size on the page to get an accurate 1:1 rendering:

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

Please remember that when you set the width/height members of a canvas object the picture is cleared (even if you are setting the same value currently present).

Upvotes: 4

Related Questions