I'm making a game where the bubbles (circles) appear on the screen and move upwards and I'm using HTML5 and JavaScript only which means no frameworks like kinetic and no jQuery at all.
I've e to a point where I want to add an event listener to the bubble itself, now I understand that because the bubble is an object on the canvas, it has no method 'addEventListener' so I can't directly add a click event to the bubble, I was wondering if anybody could help me with this problem I'm having? Here is a fiddle of what happens so far...
Bubbles
I have tried to add the event listener to the bubble as specified before by doing this...
bubbles[i].addEventListener('click', function);
I have also tried adding mouseevents such as
bubbles[i].onmouseenter = function () { console.log("blah") }
But now, I'm seriously at a loss
Thanks in advance!
I'm making a game where the bubbles (circles) appear on the screen and move upwards and I'm using HTML5 and JavaScript only which means no frameworks like kinetic and no jQuery at all.
I've e to a point where I want to add an event listener to the bubble itself, now I understand that because the bubble is an object on the canvas, it has no method 'addEventListener' so I can't directly add a click event to the bubble, I was wondering if anybody could help me with this problem I'm having? Here is a fiddle of what happens so far...
Bubbles
I have tried to add the event listener to the bubble as specified before by doing this...
bubbles[i].addEventListener('click', function);
I have also tried adding mouseevents such as
bubbles[i].onmouseenter = function () { console.log("blah") }
But now, I'm seriously at a loss
Thanks in advance!
Share Improve this question asked Dec 28, 2013 at 13:03 user3045449user3045449 1- 2 As the bubbles aren't actually DOM elements, you can't bind events to them. Instead I suggest you bind a mousemove event to your canvas and get the relative mouse coordinates. When you have these, you can loop through your bubbles array to check if the mouse is inside any of them. – Jacob Lauritzen Commented Dec 28, 2013 at 13:48
1 Answer
Reset to default 4I have updated your sample on jsfiddle demonstrating hit-testing. This sample uses an onmousemove event handler bound to the canvas and performs the actual hit-test when this event occurs. The hit-test in your case is "Is the mouse coordinate with in the bubble's circle?"
Summary of changes:
- A "bubble" has a color property to demonstrate the effect of a hit test.
function hitTest(x, y) { ... }
used to test whether the passed in coordinates are within the bubble.function getMouse(e, canvas) ...
used to transform the mouse coordinates to canvas relative coordinates. i.e, the mouse coordinate needs to be relative to the upper left hand corner of the canvas to be accurate.