简体   繁体   English

在没有Jquery的情况下在Canvas上进行鼠标坐标

[英]Mouse coordinates on Canvas without Jquery

I am currently using: 我目前正在使用:

e.pageX - $("#canvas").offset().left

This is the only thing I am using Jquery for, so I would prefer to re-write this using just javascript. 这是我使用Jquery的唯一功能,因此我宁愿仅使用javascript进行重写。

What can I use to replace this? 我可以用什么来代替它?

The answer provided by N Rohler works well only in Internet Explorer (with some bugs prior to IE8 - but I guess it won't be a problem for you since you're using a canvas and pageX), and in Opera if the padding is 0, and in Safari/Chrome if the border width is 0 too. N Rohler提供的答案仅在Internet Explorer(带有IE8之前的一些错误-但我想这对您来说不会有问题,因为您使用的是canvas和pageX)和Opera中(如果填充是0,如果边框宽度也是0,则在Safari / Chrome中也是如此。 In Firefox, unfortunately, offsetX and offsetY are undefined. 不幸的是,在Firefox中,offsetX和offsetY是未定义的。 http://www.quirksmode.org/dom/w3c_cssom.html#mousepos http://www.quirksmode.org/dom/w3c_cssom.html#mousepos

Kaninepete, I think you should reconsider, for the sake of simplicity, the way of getting the mouse coordinates relatively to your canvas element. Kaninepete,为简单起见,我认为您应该重新考虑使鼠标相对于画布元素相对应的方式。 All you have to do is to calculate the position of the canvas, which is a pretty simple task using .getBoundingClientRect() (also, don't forget to add scroll offsets if necessary), and subtract it from pageX and pageY. 您要做的就是计算画布的位置,这是使用.getBoundingClientRect()的一项非常简单的任务(此外,请不要忘记在必要时添加滚动偏移量),并将其从pageX和pageY中减去。

var x = e.offsetX,
    y = e.offsetY;

Updated (again) for (correct) Firefox compatibility: 更新(再次)以实现(正确)Firefox兼容性:

var rect = e.target.getBoundingClientRect();
var x = e.offsetX || e.pageX - rect.left - window.scrollX,
    y = e.offsetY || e.pageY - rect.top - window.scrollY;

You can replace it by the below code 您可以将其替换为以下代码

<canvas onmouseDown="mouseDown(event)" width="500" height="500"></canvas>


function mouseDown(e)
{
  var x=e.clientX-canvas.offsetLeft;
  var y=e.clientY-canvas.offsetTop; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM