2014-09-22 59 views
1

我一直在試圖與HTML 5這一簡單的動畫和JavaScript從這裏動畫:超時功能使用JavaScript畫布

http://www.developphp.com/view.php?tid=1262

的代碼follwoing:

<!-- Lesson by Adam Khoury @ www.developphp.com --> 
<!-- Watch the video to get code explanation line by line --> 
<!-- http://www.youtube.com/watch?v=hUCT4b4wa-8 --> 
<!DOCTYPE html> 
<html> 
<head> 
<style type="text/css"> 
canvas{border:#666 1px solid;} 
</style> 
<script type="text/javascript"> 
function draw(x,y){ 
    var canvas = document.getElementById('canvas'); 
    var ctx = canvas.getContext('2d'); 
    ctx.save(); 
    ctx.clearRect(0,0,550,400); 
    ctx.fillStyle = "rgba(0,200,0,1)"; 
    ctx.fillRect (x, y, 50, 50); 
    ctx.restore(); 
    x += 1; 
     var loopTimer = setTimeout('draw('+x+','+y+')',100); 
} 
</script> 
</head> 
<body> 
<button onclick="draw(0,0)">Draw</button> 
<canvas id="canvas" width="550" height="400"></canvas> 
</body> 
</html> 

有隻是一件事我不明白在代碼中:在setTimeout方法'+'之前和之後xy做什麼,爲什麼報價是我們ED附上+x++y+?

+0

它將一個字符串與一個變量連接起來。 – 2014-09-22 09:16:47

+0

重複[調用setTimeout()函數](http://stackoverflow.com/questions/3800512/calling-functions-with-settimeout)?? – karan3112 2014-09-22 09:17:36

回答

0

的setTimeout的將一個eval執行該指令,我的意思是當超時彈出,這將執行:

eval('draw('+x+','+y+')'); 

如果你不喜歡這種語法,我個人不要「T,你可以使用這個:

var loopTimer = setTimeout(function() { 
    draw(x,y); 
},100); 
+0

謝謝。是否可以在同一個上下文中從畫布的右下方向左下方畫出另一個綠色的小矩形? – student101 2014-09-22 10:03:56

+0

是的,這是可能的,但你需要參數化在ctx.fillStyle =「rgba(0,200,0,1)」中使用的顏色,以及在x + = 1中使用的方向;你的函數頭看起來應該像函數draw(x,y,color,direction);你會叫它2次 – Balder 2014-09-22 10:10:10

4

'draw('+x+','+y+')'這是一個公正的字符串concatination你會通過打印字符串明白這一點。跟隨小提琴解釋更多。

http://jsfiddle.net/zebqqcee/