鼠标事件未在html5画布上触发

时间:2021-04-29 23:58:17

I would like to know if there is any special way that one would use to register events for html5 canvas elements?

我想知道是否有任何特殊的方式可以用来为html5 canvas元素注册事件?

The following code won't raise any mouse events on my canvas elements:

以下代码不会在我的canvas元素上引发任何鼠标事件:

function MyObject() {
   this.init();
};

MyObject.prototype.init = function() {
   var canvas = document.getElementById('myCanvas');
   var ctx = canvas.getContext('2d');
   var anImage = new Image('image1.png');

   ctx.drawImage(anImage, 0, 0, 100, 100, 0, 0, 100, 100);

   canvas.onmousedown = createDelegate(this, this.mouseDownEvent);
}

MyObject.prototype.mouseDownEvent = function(e) {
    //Not even reaching this point.
}

var obj = new MyObject();

the mouseDownEvent function is not even getting called when I click on the canvas. Can anybody tell me whats wrong with the code.

单击画布时,甚至没有调用mouseDownEvent函数。任何人都可以告诉我代码有什么问题。

N.B. Swapping out the canvas for image tags fixes the problem.

注:更换图像标签的画布可以解决问题。

2 个解决方案

#1


1  

Ok, I know this is strange but by adding a

好的,我知道这很奇怪,但添加一个

-webkit-transform: translate3d(0, 0, 0)

styling to the canvas element seems to have fixed the issue...weird.

样式到画布元素似乎已经解决了这个问题......很奇怪。

#2


1  

This is a little late, but I just had a similar experience. I detailed it here: Putting HTML5 <canvas> inside <table> nullifies mouse events. It turns out that the mouse events were still triggering, but all my calculated coordinates were way off due to be calculating relative to the wrong offset.

这有点晚了,但我有类似的经历。我在这里详细说明:将HTML5 放在

中会使鼠标事件无效。事实证明,鼠标事件仍在触发,但由于相对于错误的偏移计算,我所有计算出的坐标都没有了。

This is probably too late to help you, but maybe it'll satisfy your intellectual curiosity?

这可能为时已晚,无法帮助您,但也许它会满足您的求知欲?

#1


1  

Ok, I know this is strange but by adding a

好的,我知道这很奇怪,但添加一个

-webkit-transform: translate3d(0, 0, 0)

styling to the canvas element seems to have fixed the issue...weird.

样式到画布元素似乎已经解决了这个问题......很奇怪。

#2


1  

This is a little late, but I just had a similar experience. I detailed it here: Putting HTML5 <canvas> inside <table> nullifies mouse events. It turns out that the mouse events were still triggering, but all my calculated coordinates were way off due to be calculating relative to the wrong offset.

这有点晚了,但我有类似的经历。我在这里详细说明:将HTML5 放在

中会使鼠标事件无效。事实证明,鼠标事件仍在触发,但由于相对于错误的偏移计算,我所有计算出的坐标都没有了。

This is probably too late to help you, but maybe it'll satisfy your intellectual curiosity?

这可能为时已晚,无法帮助您,但也许它会满足您的求知欲?