这是我的代码:
<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 坐标,因此图像将动态移动,从而移动 Canvas 区域...
setTimeout('autoRun()',1000);
上面的行将每隔一秒调用自动运行函数 javascript,该函数将清除 Canvas 并使用新坐标重新绘制图像....
现在我想在单击图像时获取图像的 id。我怎样才能做到这一点?
最佳答案
编辑-这行不通! 这对你有用吗?或者还有其他并发症吗?
//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 中不可用,您只是临时创建它以将其绘制到 Canvas 中。因此 Canvas 保存图像的内容,图像本身不在 DOM 中”
关于javascript - 单击该图像时如何在canvas html5中获取图像ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10994090/