Add event listener to a drawn object on html5 canvas

I am making a game where bubbles (circles) appear on the screen and move up, and I use only HTML5 and JavaScript, which means there are no frameworks like kinetics and jQuery in general.

I came to the point where I want to add an event listener to the bubble itself, now I understand that since the bubble is an object on the canvas, it does not have the addEventListener method, so I cannot directly add a click event to the bubble, I was wondering can someone help me with this problem i am having? Here is a scenario of what is happening so far ...

Bubbles

I tried to add an event listener to the bubble as stated above by doing this ...

bubbles[i].addEventListener('click', function); 

I also tried adding mice such as

 bubbles[i].onmouseenter = function () { console.log("blah") } 

But now I'm seriously at a loss

Thanks in advance!

+1
source share
1 answer

I updated your sample on jsfiddle demonstrating hit testing. This example uses the onmousemove event handler associated with the canvas and the actual test runs when this event occurs. Test test in your case: "Is the mouse coordinate in a circle of bubbles?"

Summary of Changes:

  • "bubble" has a color property to demonstrate the effect of the hit test.
  • function hitTest(x, y) { ... } used to check if the transmitted coordinates are inside the bubble.
  • function getMouse(e, canvas) ... used to convert mouse coordinates to relative canvas coordinates. that is, the mouse coordinate must be relative to the upper left corner of the canvas in order to be accurate.
+4
source

All Articles