0

I have two images (forward arrow and back arrow) on the canvas.

<script>    
var ileri = new Image();
var geri = new Image();
ileri.src= "ileri.png";
geri.src = "geri.png";
var ilerigeri = 0;

GetFeedback = function(a){
context.drawImage(ileri,50,330);
context.drawImage(geri,300,330); 
}

</script>

....

<div id="ccontainer">
    <canvas id="myCanvas" width="600" height="400"></canvas>
</div>

I want to change the value of "ilerigeri" as 1, if ileri.png clicked. I want to change the value of "ilerigeri" as 2, if geri.png clicked. Can I use something like image.onclick or need to find coordinates of the point clicked?

user1942359
  • 1,449
  • 3
  • 13
  • 8

2 Answers2

0

The canvas element will catch the click event for himself, but you have to know what pixels are under the cursor by yourself.

Remember that the canvas tag is just a place to render in. Natively, it's not a scene graph or any object structure.

So 2 solutions at least:

  1. detect yourself which button is clicked. You can check if the cursor is inside the bounding box of the image. Something like that :

    if (mousePosition > img.x && mousePosition < (img.x + img.width) && mousePosition>img.y && mousePosition<(img.y+img.height) { // do the work }

  2. use a framework like cgSceneGraph do easily do the work for you :)

Gwennael Buchet
  • 1,247
  • 11
  • 11
0
<div id="ccontainer">
    <canvas id="myCanvas" width="600" height="400" ></canvas>
</div>

JS:

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var ileri = new Image();
var geri = new Image();
ileri.src = "ileri.png";
geri.src = "geri.png";
ileri.onload = function() {
    context.drawImage(ileri,50,330);
}

geri.onload = function() {
    context.drawImage(geri,300,330);
}



canvas.onclick = function(e) { 
   if(e.pageX >= (this.offsetLeft + 50) && e.pageY >= (this.offsetTop + 330)){
       if(e.pageX <= (this.offsetLeft + 50 + ileri.width) && e.pageY <= (this.offsetTop + 330 + ileri.height)){
          alert('ileri');
       }
   }
   if(e.pageX >= (this.offsetLeft + 300) && e.pageY >= (this.offsetTop + 330)){
       if(e.pageX <= (this.offsetLeft + 300 + geri.width) && e.pageY <= (this.offsetTop + 330 + geri.height)){
          alert('geri');
       }
   }    
   }

Here is working example, http://jsfiddle.net/wcxc2/6/

MJQ
  • 1,778
  • 6
  • 34
  • 60