【问题标题】:Create an event on a dynamically placed image on an HTML5 canvas在 HTML5 画布上动态放置的图像上创建事件
【发布时间】:2012-03-08 04:33:45
【问题描述】:

我正在通过 javascript 动态放置一个磁贴,因此对于每个磁贴我都需要一个 onclick 事件。

我正在做的是:

var image = new Image();
image.src = "tile.png";
for(var i=0;i<20;i++){
   for(var j=0;j<20;j++){
      ctx.drawImage(image,i,j,20,20,i,j,20,20);
   }
}

但是我不能在图像变量上放置一个事件,这是行不通的。 有没有可能将事件处理程序传递给 drawImage 的方法?

我只希望点击画布时获得图块编号, 请建议任何其他替代方案。 谢谢。

【问题讨论】:

  • 如果你可以在图像被渲染之前设置一个类,你可以将一个事件连接到类 $('.myclass').click(...);
  • 您可以使用像fabric.js 这样的画布库,它为您提供画布中的对象模型(您可以单独收听每个图像对象的点击)。

标签: javascript image html events canvas


【解决方案1】:

为什么它不起作用

不能在 javaScript 对象上绑定事件,您必须将其绑定到 domElement

解决方案

您需要将图像附加到一个domElement 并在那里绑定click 事件。将这些行添加到您当前的代码中:

$(".image_container").append(image).click(function () {
  //what you want to do when the canvas is clicked.
});

【讨论】:

    【解决方案2】:

    如果您使用 JQuery (1.7.1),您可以使用 live 为每个图像添加点击事件,实时将点击事件添加到 dom。所以改变你的代码如下。注释在方法中。让我知道这是否适合您。

    罗伯

    不确定您是否有一些代码可以从图像中获取磁贴,但您也许可以使用它...

    Tileset for HTML5 canvas game

    var iCount = 1
    for(var i=0;i<20;i++){
       for(var j=0;j<20;j++){
          iCount = iCount +1
    
          //create image in the loop
          var image = new Image();
          image.src = "tile.png";
          image.attr('class', 'theimage_' + iCount );
    
          //in the loop each image has a unique class name which you 
          //can attach to the dom via jquery live
          ctx.drawImage(image,i,j,20,20,i,j,20,20);
    
          //you can either attach some logic here or outside of the loop
          $('.theimage_' + iCount ).live('click', function() {
            alert("You Clicked: " + '.theimage_' + iCount );
          });
    
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2012-08-16
      • 2014-04-15
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多