0

I am working in JavaScript and I am trying to click on an object and make something simple happen, like an alert for example.

So I've declared the object as such:

var panel = new Image();
panel.src = IMAGES_PATH + "panel.png";

Then I've drawn it to the screen.

ctx.drawImage(panel, 475, 140);

The problem I am facing now is that I want to click on it and I want a function to fire.

Attempt #1

panel.onclick = function () {
    alert("You clicked!");
}

Attempt #2

panel.addEventListener('click', function ()
{
    alert('blah');
}, false);

I know the click events are working in Google Chrome because I can do:

window.addEventListener("click", click, false);

Any ideas to why I can't do an onclick for the Image class?

  • 1
    It looks like you are not putting the image into the DOM, but are only painting it onto a `canvas` element. In that case, you would have to capture clicks on the canvas element – and figure out according to dimensions and click coordinates if the click happened on the area where the image is painted onto the canvas … – CBroe Aug 09 '14 at 01:01
  • I was afraid of that... Well I guess that solves my problem –  Aug 09 '14 at 01:03

2 Answers2

0

Looks like you are using the canvas for drawing shapes. There is now way you could register click events for objects on canvas.

Please refer to this post for some good suggestions

Canvas images and Click event

Community
  • 1
  • 1
Praveen
  • 206
  • 2
  • 11
0

Thanks for the suggestion guys, I've decided to do it by getting the mouse x and y position in the canvas and working out where I can click for it to fire the event.

http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/