html5:如何处理canvas子点击事件?

html5: how to handle canvas child clicked event?

<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var imageObj = new Image();
  imageObj.onload = function() {
    context.drawImage(imageObj, 128, 128);
  };
  imageObj.src = 'http://xxx/yyy/zzz.jpg';
</script>

imageObj,canvas 对象的子对象(不是 canvas)被点击?

方法是处理 canvas 的点击事件,然后自己判断 canvas 的哪一部分被点击:

canvas.addEventListener("mouseup", doMouseClick, false);

var doMouseClick = function(event) 
{
   //Some magic to have the exact coordinates in the canvas:
   var clickPos = {
     x : event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor($(canvas).offset().left);,
     y : event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor($(canvas).offset().top) + 1 
   }

   //check the image
   if (clickPos.x > 128 && clickPos.y < 128 + imageObj.width
       && clickPos.y > 128 && clickPos.y < 128 + imageObj.height){
      console.log("Oh boy! Someone clicked the image!");
   }

}

我们之所以必须这样做,是因为您没有 "add" 您的图像作为 child 到 canvas,您 "draw" 它就在 canvas 上。 canvas 只显示像素,不知道实际绘制的是什么。