Mouse event not being triggered on html5 canvas

*爱你&永不变心* 提交于 2019-12-10 19:18:10

问题


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

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

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.

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


回答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:


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.

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



来源:https://stackoverflow.com/questions/8986972/mouse-event-not-being-triggered-on-html5-canvas

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