为什么CSS中心乱画画布鼠标坐标? [英] Why does CSS centering mess up canvas mouse coordinates?

查看:203
本文介绍了为什么CSS中心乱画画布鼠标坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的代码中,每当我用

  margin:auto; 

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

鼠标坐标被移动,并且该移位或偏移似乎依赖于尺寸



为什么鼠标坐标移动了?



有什么方法可以防止仍然得到相同的效果?

解决方案

它们确实移位鼠标坐标是相对于客户端窗口而不是画布元素本身。 / p>

我怀疑您正在使用clientX / Y,而没有补偿。



示例:位置



  function getXY(canvas,event){
var rect = canvas.getBoundingClientRect //画布的绝对位置
return {
x:event.clientX - rect.left,
y:event.clientY - rect.top
}
}

现在只要在需要鼠标位置时调用此函数:

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

这将提供调整后的位置。注意,如果使用边框或填充,那么它不会补偿边框或填充 - 在这些情况下,将画布包裹在父div中,并将边框/填充应用到该div。


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?

解决方案

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.

这篇关于为什么CSS中心乱画画布鼠标坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆