timeout函数,用于使用canvas的简单html 5 javascript动画

timeout function for simple html 5 javascript animation using canvas

本文关键字:html 简单 javascript 动画 canvas 函数 用于 timeout      更新时间:2023-09-26

我一直在尝试用html 5和javascript制作这个简单的动画:

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

代码如下:

<!-- 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之前和之后的'+'做什么,以及为什么用引号括住+x++y+?

'draw('+x+','+y+')'这只是一个字符串连接,您可以通过打印该字符串来理解这一点。下面的小提琴解释更多。

http://jsfiddle.net/zebqqcee/

setTimeout将使用eval执行指令,我的意思是当超时弹出时执行:

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

如果你不喜欢这种语法,我个人不喜欢,你可以使用这个:

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