Putting HTML5 <canvas> inside <table> nullifies mouse events

只愿长相守 提交于 2020-01-05 04:25:09

问题


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);

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.

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.

Thanks.


回答1:


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

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;

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.

I replaced those lines with these:

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

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.



来源:https://stackoverflow.com/questions/42899889/putting-html5-canvas-inside-table-nullifies-mouse-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!