0

I have created a canvas and added an image on it. I want to add a click event to that image. Below is my code for the same.

<canvas id="myCanvas" width="578" height="1000"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  //This code is for adding leftArrow icon
  var leftArrow = new Image();
  leftArrow.src = "leftArrow.jpg";

  leftArrow.addEventListener("click",function(){alert("hello");},false); //this is not working

  leftArrow.onclick=function(){alert("image click");}

    drawScreen();


  function drawScreen() {
    //context.drawImage(leftArrow, 218, 482);//leftArrow
    leftArrow.onload = function(){
              context.drawImage(leftArrow, 218, 482);
    }
  }

</script>


I want to add event to its click.

1 Answers1

0

You're assigning the click event on the leftArrow. When you draw the leftArrow on the canvas, your copying image contents, not events.

In fact, new Image() is about the same as document.createElement("img") - you get a <img ...>.

So, to assign click event to the canvas, you have to do this:

canvas.addEventListener("click", function() {alert("click");});

If you only want to check whether the click is within a rectangle where the arrow is, you will need to get the click offsets and calculate it:

var x,y; //Click offsets, here I assume they already have the value
var posx, posy; //Position of the arrow, the values you used as .drawImage parameters
var endx = posx + leftArrow.width;
var endy = posy + leftArrow.height;
if( (x>posx && y>posy) && (x<endx && y<endy) )
   alert("Arrow was clicked!");

Aditionally, never assign onload to image after you set up the src attribute. The image loads asynchronously and there's a possibility that it loads before you set up the onload event.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • Thank you for the answer, But I want the click event to happen only when I click on the Image but not on the entire canvas. – Krishna Somayajulu Nov 15 '14 at 17:16
  • There's no `Image` on that canvas. The whole `canvas` is one image. The only thing you can do is to use the [click coordinates on that canvas](http://stackoverflow.com/a/4430498/607407) to calculate whether it's on the arrow or not. By using canvas rendering you're basically throwing away all the benefits of DOM. – Tomáš Zato Nov 15 '14 at 17:18
  • So i have to again find the coordinates of where the click happened on canvas and if coordinates match that of the Image I add my function there. Is it? – Krishna Somayajulu Nov 15 '14 at 17:21
  • Yes. I strongly suggest you try to render arrow as separate HTML element. Did you know that [SVG images can be animated using JavaScript](http://u8.8u.cz/pokus.svg)? – Tomáš Zato Nov 15 '14 at 17:29