Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener in Canvas tag

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)

like image 572
kadiks Avatar asked Oct 07 '09 16:10

kadiks


People also ask

Does canvas support event handlers?

The Canvas event handling system closely follows the W3C DOM Event Model. If you have already used events in JavaScript and HTML most concepts of the Canvas event system should be already familiar to you. The most notable difference is the missing capture phase, but it is usually not used anyhow.

What is addEventListener in HTML?

Definition and Usage. The addEventListener() method attaches an event handler to an element.

Is it better to use onclick or addEventListener?

Summary: addEventListener can add multiple events, whereas with onclick this cannot be done. onclick can be added as an HTML attribute, whereas an addEventListener can only be added within <script> elements.


2 Answers

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?"

like image 105
Borgar Avatar answered Sep 22 '22 13:09

Borgar


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.

like image 32
Sujay Avatar answered Sep 24 '22 13:09

Sujay