Html5, adding an eventlistener to a drawn image on canvas

I am experimenting with html5 and I have a small drop-down image, the user selects both the image and draws it on the canvas using drawImage ();

I cannot figure out how to add an event listener to a newly drawn image on canvas.

I tried to put it in a variable like:

var newImg = ctx.drawImage(myImage, 200, 200); 

and then adding an eventlistener to this, but it doesn't work.

 newImg.addEventListener('mousedown', onImgClick, false); 

What is the right way to do this.

+6
javascript html5
source share
3 answers

If you are looking for such interactivity, <canvas> is probably not what you want. You are looking for SVG . There is a fantastic library called Raphaël that allows you to work with the SVG piece of cake in all browsers, even on IE6. It is also fully compatible with jQuery , so you can:

 var paper = Raphael(10, 50, 320, 200); var img = paper.image("/path/to/img.png", 10, 10, 80, 80); $(img).click(onImgClick); 

I am sure that it will be better for you and be easier to use than <canvas> .

Note. Raphaël has some helpers for major events, such as "click" and "mousedown", just do img.click(onImgClick) , but if you already use the jQuery library, which you probably know, I would recommend consistency and use of processing library events.

+7
source share

Canvas is not a saved mode . It is just a flat image; there is no object for event binding in it, and drawImage nothing.

You will need to detect the clicks on <canvas> and check if they are inside the rectangle [200, 200, 200 + w, 200 + h] manually. Or, if you want to draw in saved mode, consider using SVG instead of canvas.

+5
source share

To do this without the help of JS:

Although you cannot attach an event listener to the context you call drawImage () on; You can attach event listeners to the canvas itself.

 myCanvasElement = document.getElementById('canvasElement'); myCanvasElement.addEventListener("click", someFunction, false); 

If you need to get this image that you are painting, you could probably stack canvas objects and create a new one for each image you paint.

0
source share

All Articles