2014-09-22 60 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/