addEventListener in Canvas tag

孤者浪人 提交于 2019-12-17 23:46:17

问题


I have a canvas tag to create a graphic. At each section of my line, I have a "dot" to enable a 'mouseover' and display more detail.

Everything works fine when I don't add an event listener to this dot.

Firebug is warning me : s.addEventListener is not a function...

Is it possible to create dynamic event listener? (I'm new to Javascript)


回答1:


You cannot attach DOM events to things other than DOM objects (elements). The canvas is a DOM element, the things you are drawing to the canvas are not. They become a part of the canvas as pixels of an img.

In order to detect a click on a specific point on your canvas you must attach the click event on the canvas element, and then compare the x/y coordinates of the click event with the coordinates of your canvas.

This was answered in: "How do I get the coordinates of a mouse click on a canvas element?"




回答2:


If you're gonna be drawing basic structures, I suggest you make use of inline svg.

In this case, all the svg elements become DOM elements and you can attach separate events to each of them.



来源:https://stackoverflow.com/questions/1532739/addeventlistener-in-canvas-tag

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