无法制作可点击的图片

时间:2014-04-08 17:11:40

标签: javascript

我有一个问题,就是可以点击一个对象的图像,这就是代码:

    // 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'); };

它会预览图标,但是当我点击它时没有任何反应,javascript编码是否正确?

首先尝试 onclick ,但点击图标时没有显示任何内容

2 个答案:

答案 0 :(得分:1)

Canvas元素本身支持/检测事件,但画布内的对象不支持。 要实现这一点,您必须在画布和触发事件中跟踪鼠标坐标。

检查此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);

答案 1 :(得分:0)

icon1.img1.onclick = function() 
        { alert('blah'); };

以下是一种更方便的方法,因为您可以在必要时安全地删除事件监听器

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

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

// removig
// icon1.img1.removeEventListener('click', clickHandler);