我正在努力使画布内的图像可以点击,但我很困惑如何去做,这是我目前所拥有的,我只是希望图片[0]可点击并且一旦它发出警报单击,但由于某种原因它不起作用。如何制作它以便在单击图片[0]时警报响起。
var images = document.getElementsByTagName("img");
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var left = c.offsetLeft;
var top = c.offsetTop;
var pictures = [];
//wheel
pictures[0] = new Image();
pictures[0].src = 'images/Layer8.png';
//bg
pictures[1] = new Image();
pictures[1].src = 'images/Layer0.png';
//gear
pictures[2] = new Image();
pictures[2].src = 'images/Layer7.png';
//speed
pictures[3] = new Image();
pictures[3].src = 'images/Layer14.png';
//dial1
pictures[4] = new Image();
pictures[4].src = 'images/Layer18.png';
//dial2
pictures[5] = new Image();
pictures[5].src = 'images/Layer16.png';
//dial3
pictures[6] = new Image();
pictures[6].src = 'images/Layer17.png';
c.addEventListener('click', function(event){
var x = event.pageX - left,
y = event.pageY - top;
pictures.forEach(function(fx,fy,fwidth,fheight,x,y) {
if (y > fy && y < fy + fheight
&& x > fx && x < fx + fwidth) {
alert('clicked an element');
}
});
}, false);
function load(){
ctx.drawImage(pictures[1],0,0);
ctx.drawImage(pictures[2],468,263);
ctx.drawImage(pictures[3],89,77);
ctx.drawImage(pictures[4],146,153);
ctx.drawImage(pictures[5],278,153);
ctx.drawImage(pictures[6],206,119);
ctx.drawImage(pictures[0],fx,fy,fwidth,fheight);
}
var fx = 84;
var fy = 60;
var fwidth = 283;
var fheight = 276;
window.onload = load;
答案 0 :(得分:1)
好的,我明白你要做什么。不幸的是,画布中的图像不是DOM元素,只有画布本身就是一个。这意味着使用jQuery,您可以调用:
$('#myCanvas').on('click', function() {});
或原生:
c.addEventListener('click', function(){});
但是,在这种情况下,fabricjs.com库可能对您有用。