简体   繁体   English

在多个图像上画布HTML5单击事件

[英]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. 画布HTML5对我来说是全新的。 So how can I set a click event on each images in my canvas ? 那么如何在画布中的每个图像上设置click事件呢?

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. 您可以做的是构建自己的click事件处理代码。

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. 然后,通常为canvas.onclick添加一个侦听器, canvas.onclick处理函数将鼠标坐标与您保存的坐标进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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