Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

javascript - Why does CSS centering mess up canvas mouse coordinates?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...