将click事件添加到画布上的Image

时间:2014-11-15 17:08:54

标签: javascript html5 canvas html5-canvas

我创建了一个画布并在其上添加了一个图像。我想向该图像添加一个click事件。下面是我的相同代码。

<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>


我想在其点击中添加事件。

1 个答案:

答案 0 :(得分:0)

您正在leftArrow分配点击事件。当您在leftArrow上绘制canvas时,复制图像内容,而不是事件

事实上,new Image()document.createElement("img")大致相同 - 您获得<img ...>

因此,要将click事件分配给画布,您必须执行以下操作:

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

如果您只想检查点击是否在箭头所在的矩形内,您需要获取点击偏移并计算它:

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!");

在设置onload属性之后,从不src分配给。图像以异步方式加载,并且在设置onload事件之前可能会加载