放置HTML5< canvas>里面< table>使鼠标事件无效 [英] Putting HTML5 <canvas> inside <table> nullifies mouse events

查看:286
本文介绍了放置HTML5< canvas>里面< table>使鼠标事件无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML5 canvas对象,它多次使用 addEventListener()方法,以便能够响应鼠标事件。我使用的行看起来像这样:

I have an HTML5 canvas object, that uses the addEventListener() method multiple times, to be able to respond to mouse events. The lines I use looks like this:

canvas.addEventListener(mousemove,this.checkMouseLocation.bind(this,this.inputs), false);

只要画布直接位于文档的正文或div中,这一切都能很好地工作。但是,它在表中不起作用。将画布放在那里后,所有鼠标事件似乎都会停止触发。

This all works perfectly well, so long as the canvas is directly inside the document's body, or in a div. However, it doesn't work inside a table. Once the canvas is placed there, all the mouse events appear to stop firing.

阅读鼠标事件未在html5画布上触发,我决定尝试该解决方案 - 添加属性 style = -webkit-transform:translate3d(0,0,0);到我的画布。这解决了Firefox中的问题,但在Chrome中它仍然拒绝关注鼠标。

After reading Mouse event not being triggered on html5 canvas, I decided to try that solution--to add the property style="-webkit-transform: translate3d(0, 0, 0);" to my canvas. This fixed the issue in Firefox, but in Chrome it still refuses to pay attention to the mouse.

有没有人有任何想法?最好的猜测是这与鼠标坐标有关,但我无法告诉你如何。

Does anybody have any ideas? Best guess is that this has something to do with mouse coordinates, though I couldn't tell you how.

谢谢。

推荐答案

我找到了答案,对于任何跟我来的人。

I found the answer, for any who come after me.

鼠标消息并非完全没有 - - 他们还在发生。然而,鼠标的x和y坐标完全关闭,直到它没有响应它们。

The mouse messages weren't totally nixed--they were still happening. However, the mouse's x and y coordinates were totally off, to the point where it wasn't responding to them.

我一直在通过减去画布来计算我的鼠标坐标偏离鼠标的位置,如下所示:

I had been calculating my mouse's coordinates by subtracting the canvas's offset from the mouse's location, like this:

var x = event.pageX - canvas.offsetLeft;
var y = event.pageY - canvas.offsetTop;

不幸的是,这不可靠,因为画布对象的偏移量并不总是与文档正文有关。当在表格内时,它们相对于< td> 画布在里面。所以坐标离开了,使 canvas 对象看起来完全没有响应鼠标。

Unfortunately, this isn't dependable, because the canvas object's offsets aren't always with respect to the document body. When inside a table, they were relative to the <td> the canvas is inside. So the coordinates were way off, making the canvas object appear to be totally nonresponsive to the mouse.

我更换了这些行:

var rect = canvas.getBoundingClientRect();
var x = event.clientX - rect.left;
var y = event.clientY - rect.top;

这似乎有点笨拙,因为众神只知道 getBoundingClientRect的效率()函数是,这意味着我正在处理浮点坐标而不是整数坐标。但是我计算的x和y是准确的,而且更重要。

This seems a little kludgey, since the gods only know how efficient the getBoundingClientRect() function is, and it means that I'm dealing with floating-point coordinates rather than integer coordinates. But the x and y I calculate are accurate, and that's more important.

我希望这有助于其他人在路上。

I hope that this helps someone else down the road.

这篇关于放置HTML5&lt; canvas&gt;里面&lt; table&gt;使鼠标事件无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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