1

I'm making a simple HTML5 canvas drawing app for fun.

In my code, whenever I center the canvas with

margin: auto;

or

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

the mouse coordinates are shifted, and that shift, or offset, seems to be reliant upon on the size of the window.

Why are the mouse coordinates shifted?

Is there any way to prevent this, while still getting the same effect?

Elegant.Scripting
  • 757
  • 4
  • 10
  • 28

1 Answers1

5

They are indeed shifting as mouse coordinates are relative to client window not the canvas element itself.

I suspect you are using the clientX/Y as-is without compensating for this.

Example: correcting mouse positions

function getXY(canvas, event) {
    var rect = canvas.getBoundingClientRect();  // absolute position of canvas
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    }
}

Now simply call this function each time you need the mouse position:

function onmousemove(e) {
    var pos = getXY(canvas, e);
    console.log(pos.x, pos.y);
}

This will provide adjusted position. Notice it does not compensate for border or padding if you use that - in those cases, wrap canvas in a parent div and apply border/padding to that div instead.

Community
  • 1
  • 1
  • 1
    @kba thanks! This is a very thorough answer, and works perfectly. I was a little shocked, you knew exactly where I was going wrong! You seem like a very experienced developer when it comes to Javascript, are there any books you recommend? – Elegant.Scripting Apr 07 '15 at 21:40