0

I have two images inside a <canvas> element.

var ctx = document.getElementById('canvas').getContext('2d');

var img1 = new Image();
img1.src = 'cloud.jpg';
img1.name = "Image 1";
img1.onload = function() {
    ctx.drawImage(img1, 0, 0);
};

var img2 = new Image();
img2.src = 'eleph.png';
img2.name = "Image 2";
img2.onload = function() {
    ctx.drawImage(img2, 250, 250);
};

Now, when User clicks inside canvas, I want to find which object was clicked. For example, alert img1.name or img2.name when user clicks corresponding image inside the canvas.

Please give some directions as how to do this. Thanks!

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • what have you tried so far? `alert()` or `console.log()`? to capture the click event? – Jakub Feb 11 '12 at 01:58
  • Normally you'll need to use a [shadow canvas](http://stackoverflow.com/a/6604825/707111). – Ry- Feb 11 '12 at 02:06
  • I have tried alert(e.target.name) and its returning me the canvas object. –  Feb 11 '12 at 03:39
  • This would be trivial is you used canvas library like [fabric.js](http://fabricjs.com). – kangax Feb 11 '12 at 17:47
  • Thanks minitech! It solves my problem in a certain way, but I am thinking it would be a memory load to browser if I am using animated image inside canvas. –  Feb 11 '12 at 20:29

1 Answers1

0

First of all, you must have stored in some variable the position and size of each image. After that, add an onclick handler on you canvas element that iterate over the image position collection checking which one is under the mouse on the click event.

Mikhas
  • 851
  • 1
  • 12
  • 31
  • Thanks Mikhas! The image I am using is a transparent PNG. From what I understand from your reply, I think the onclick will work on whole part of the image and not the non-transparent part. Correct me if I am wrong. –  Feb 11 '12 at 20:35
  • In fact, it would work for the entire image, includind the transparent area – Mikhas Feb 13 '12 at 02:19
  • hi @Mikhas, did you solve your problem? Let me know, as I am facing similar problem. – a3.14_Infinity Mar 24 '16 at 03:26
  • The solution described above should fit you. You need to add some extra code to save the position of your images instead of expecting the DOM api to provide it. – Mikhas Mar 28 '16 at 20:19