Why does CSS centering mess up canvas mouse coordinates?

前端 未结 1 382
野趣味
野趣味 2020-12-21 23:43

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

In my code, whenever I center the canvas with

margin: auto;

or



        
相关标签:
1条回答
  • 2020-12-22 00:25

    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.

    0 讨论(0)
提交回复
热议问题