单击该图像时如何在画布html5中获取图像ID?

时间:2012-06-12 09:44:02

标签: javascript html5

 Here is my code
   <body>
   <canvas id="myCanvas" width="1100" height="600" style="border:1px solid #c3c3c3; cursor:move">
    Your browser does not support the canvas element.
   </canvas>

   <script type="text/javascript">

   var c=document.getElementById("myCanvas");

   var ctx=c.getContext("2d");
   var img=new Image();
   img.src="image.jpg";
   img.id="im";

   img.onload = function(){
   ctx.drawImage(img,0,0,100,100);
   autoRun();
   };
   function autoRun(){
    ctx.clearRect(0, 0, 1100,600);
    img.id="im";
    ctx.drawImage(img,Math.floor((Math.random()*1000)+1),Math.floor((Math.random()*500)+1),70,70);
    setTimeout('autoRun()',1000);

     }


</script>
</body>

这里我使用随机方法设置X和Y坐标因此图像将动态移动将移动画布区域...

 setTimeout('autoRun()',1000);

以上行将每秒调用自动运行函数javascript,该函数将清除画布并使用新坐标重绘图像....

现在我想在点击它时获取图像的ID ..怎么做?????? PLZ任何人帮助我

2 个答案:

答案 0 :(得分:1)

编辑 - 这不行! 这对你有用吗?还是有其他并发症吗?

//This would bind to all image, but you can use
//other jquery selectors to select your perticular 
//image
$('img').click(function(){
  var my_id = $(this).attr('id');
  return false;
});

修改

“..图像本身在DOM中不可用,你只是暂时创建它以将其绘制到画布中。因此画布保存图像的内容,图像本身不在DOM中”

Select image within canvas with jQuery

答案 1 :(得分:1)

我认为您应该对image的形状进行分段(定义其边界像素),然后检查当您在canvas内部单击时,选择的点(点击时的鼠标位置)是否在内部图像shape

这可以解决您的问题。