0

I have an issue with making an image of an object clickable this is the code:

    // JavaScript Document

    // Create the canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 512;
    canvas.height = 512;
    //draw canvas
    document.body.appendChild(canvas);
    var x=30;
    var y=30;

    var icon1 = new Object();
    icon1.id=1;
    icon1.selected=false;
    icon1.img1 = new Image();
    icon1.img1.onload = function() {
            ctx.drawImage(icon1.img1, 69, 50,x,y);
          };
    icon1.img1.src = 'images/hero.png';
    icon1.img1.clicked = function() 
        { alert('blah'); };

it previews the icon but when I click it nothing happens , is the javascript coding correct?

ALso tried at first onclick but the same nothing appears when clicking the icon

Phil_Charly
  • 137
  • 13

2 Answers2

1

Canvas element itself support/detect events but objects inside the canvas doesn't. To implement this you have to track mouse cordinates within the canvas and fire events.

check this fiddle

// JavaScript Document
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 512;
//draw canvas
document.body.appendChild(canvas);
var x=30;
var y=30;

var icon1 = new Object();
icon1.id=1;
icon1.selected=false;
icon1.img1 = new Image();
icon1.img1.onload = function() {
    ctx.drawImage(icon1.img1, 69, 50,x,y);
};
icon1.img1.src = 'http://icons.iconarchive.com/icons/vargas21/aquave-metal/512/Sample-icon.png';

//Add event listner to the canvas
canvas.addEventListener('click', function(e) { 
    //add mouse tracking here
    console.log('inside canvas');
    var clickedX = e.pageX - this.offsetLeft;   //Get click cordinates
    var clickedY = e.pageY - this.offsetTop;
    //check if the click is within the image's area
    if (clickedX < x + 69 && clickedX > x && clickedY > y && clickedY < y + 50) {   
        alert ('clicked');   //Put image click handling here
    }
}, false);
Mohit
  • 2,239
  • 19
  • 30
0
icon1.img1.onclick = function() 
        { alert('blah'); };

The below is a more convenient way as you could remove the event listener safely if necessary

var clickHandler = function(){
     alert('blah');
};

// adding
icon1.img1.addEventListener('click', clickHandler);

// removig
// icon1.img1.removeEventListener('click', clickHandler);
Easwar Raju
  • 253
  • 1
  • 4
  • make sure that `onclick` is completely in lower case – Easwar Raju Apr 08 '14 at 17:27
  • Thx for the effort appreciated , I 've tried yours suggestions it didn't, now I found a similar question : http://stackoverflow.com/questions/10710579/make-clickable-region-in-canvas-to-change-image – Phil_Charly Apr 08 '14 at 17:39