user2836518
user2836518

Reputation:

Assign a click event to Image object

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?

Upvotes: 0

Views: 1003

Answers (2)

user2836518
user2836518

Reputation:

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/

Upvotes: 0

Praveen
Praveen

Reputation: 236

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

Upvotes: 0

Related Questions