2015-07-04 86 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>