2012-06-12 75 views
0
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坐标,因此图像会动态移动将移动画布的区域...如何在Canavs html5中点击图片时获取图片ID?

setTimeout('autoRun()',1000); 

上面一行将调用自动运行功能的JavaScript每一个秒和功能将清除画布和重绘新坐标图像....

现在我想获得的图像的ID,当我们点击它。如何做到这一点??? ?? PLz任何人都可以帮我

+0

类似于img.onclick(alert(this.id)); – jacktheripper

+0

我在jQuery中试了很多,但没有结果 –

+1

画布元素没有点击事件。参见[中的addEventListener Canvas标签(http://stackoverflow.com/a/1532961)和[我如何获得一个canvas元素上点击鼠标的坐标?](http://stackoverflow.com/q/55677 ) – Stefan

回答

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; 
}); 

编辑

” ..The图像本身是不是在DOM可用,您刚刚创建它暂时把它画到画布,所以画布保持图像的内容时,图像本身是不是在DOM”

Select image within canvas with jQuery

+0

我之前已经尝试过,但没有工作 –

+0

刚刚发现这一点。您无法选择画布内的元素,请参阅我的编辑 – Anand

+0

谢谢感谢您的帮助 –

1

我想你应该细分image(界定其边界像素)的形状,然后检查,如果当你点击INSI点canvas,选中的点(点击时的鼠标位置)在图像的内部shape

这可以解决您的问题。