2015-07-04 40 views
0

我试图根据点击数是偶数还是奇数来改变点击画布上的图像。 基本上我想做一个零和交叉游戏,其中画布上的图像更改为交叉或零,具体取决于鼠标点击的次数。如何跟踪点击画布上的计数?请帮忙。 请指导我,因为我是一名html初学者。如何在点击时更改画布图像?

<!DOCTYPE html> 
<head> 
<title> samp1 </title> 
</head> 
<body> 
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;"> 
</canvas> 
<style> 
#mycanvas { 
margin-top:10px; 
margin-left:10px; 
} 
</style> 
<img src="http://images.all-free- download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100"/> 
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100"/> 
<script> 
var i=0; 
function fn(){ 
if(i%2==0) 
ctx.drawImage(im,0,0,can.width,can.height); 
else 
ctx.drawImage(in,0,0,can.width,can.height); 
i++;} 
var can = document.getElementById("mycanvas"); 
     var ctx = can.getContext("2d"); 
var im=document.getElementById("my"); 
var in=document.getElementById("ny"); 
can.addEventListener("click", fn, false); 
</script> 
</body> 
</html> 
+0

也许如果你给图像相同的类。并使用.toggle()在图像之间切换。 http://api.jquery.com/toggle/ – Joep

+0

@rahul是与您的问题有关的例子吗?我认为这与你在这个问题上所说的还有很大差距。 –

回答

0

我看到2个非常小的错误:

  • '中' 是在JavaScript保留字。
  • 你在URL中的空间为“我” img元素

有了这些修正你的代码应该工作,你想要的方式。

这里是一个小提琴证明: http://jsfiddle.net/w09tyftt/1/

<style> 
    #mycanvas { 
     margin-top:10px; 
     margin-left:10px; 
    } 
</style> 
<canvas id="mycanvas" width="200" height="100" style="border:1px solid #000000;"> 
<img src="http://images.all-free-download.com/images/graphicthumb/roses_554954.jpg" id="my" width="200" height="100" /> 
<img src="http://images.all-free-download.com/images/graphicthumb/flower_lighting_554944.jpg" id="ny" width="200" height="100" /> 
<script> 
    var i = 0; 

    function fn() { 
     if (i % 2 == 0) ctx.drawImage(im, 0, 0, can.width, can.height); 
     else ctx.drawImage(vin, 0, 0, can.width, can.height); 
     i++; 
    } 
    var can = document.getElementById("mycanvas"); 
    var ctx = can.getContext("2d"); 
    var im = document.getElementById("my"); 
    var vin = document.getElementById("ny"); 
    can.addEventListener("click", fn, false); 
</script>