0
<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>

How can I get notified or hooked with an event handler, when the imageObj, the child of the canvas object (not the canvas) is clicked?

David
  • 15,894
  • 22
  • 55
  • 66

1 Answers1

1

The way to do this, is by handling the click event of the canvas, and then figure out yourself what part of the canvas is clicked:

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!");
   }

}

The reason why we have to do it this way, is because the you don't "add" your image as a child to the canvas, you "draw" it on the canvas. The canvas just shows pixels and has no idea what is actually drawn.

Jordumus
  • 2,763
  • 2
  • 21
  • 38
  • You'd better retrieve the canvas position using getBoudingClientRect. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect – GameAlchemist Apr 01 '15 at 12:53
  • how to add the image as a child of the canvas? Thanks! – David Apr 01 '15 at 13:02
  • @David you can't "add it as a child". That's not the way it works. you have to check it the way I did above. If you want imageObj to be available in my funciton, just make it a global var. – Jordumus Apr 01 '15 at 13:04