简体   繁体   中英

Canvas HTML5 click event on multiple images

I have multiple images in my canvas. I have one big image and in this I have other images. I took this fiddle example .

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

var img1 =   loadImage('http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png', main);
var img2 = loadImage('http://introcs.cs.princeton.edu/java/31datatype/peppers.jpg', main);

var imagesLoaded = 0;
function main() {
  imagesLoaded += 1;

  if(imagesLoaded == 2) {
      // composite now
      ctx.drawImage(img1, 0, 0);

      ctx.globalAlpha = 0.5;
      ctx.drawImage(img2, 0, 0);
  }
}

function loadImage(src, onload) {
  // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being- called
  var img = new Image();

  img.onload = onload;
  img.src = src;

  return img;
}

The canvas HTML5 are totally new for me. So how can I set a click event on each images in my canvas ?

When you draw an image to a canvas it is not added to it as an image but as a bunch of color values. There is no way to check later which operation caused which pixels to take which colors. Event handling is simply out of scope for canvas.

What you can do is build your own click event handling code.

When you draw an image to the canvas, save the coordinates, width and height. Then add a listener for canvas.onclick in general, and have the handler function compare the mouse coordinates with the coordinates you saved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM