我正在尝试使用for循环和setInterval为canvas创建动画,但到目前为止还没有运气......这就是我的代码中的内容:
//loop function
function loop(){
var dynamic = 0;
var v = 10;
var x, y;
for (dynamic = 0; dynamic < v; dynamic++) {
x = dynamic * 1;
y = dynamic * 1;
c.clearRect(0, 0, 350, 350);
c.fillStyle = '#87CEEB';
c.beginPath();
c.arc(x, y, 10, 0, Math.PI*2, false);
c.fill();
}
}
setInterval(loop, 20);
提前非常感谢!
答案 0 :(得分:1)
也许您应该将dynamic
变量移到外面?您似乎每隔loop
在同一点绘制圆圈。
var dynamic = 0;
//loop function
function loop(){
var v = 10;
var x, y;
x = dynamic * 1;
y = dynamic * 1;
c.clearRect(0,0, 350,350);
c.fillStyle = '#87CEEB';
c.beginPath();
c.arc(x,y, 10, 0, Math.PI*2, false);
c.fill();
++dynamic;
}
setInterval(loop,20);
答案 1 :(得分:1)
如上所述:将动态移出动画循环并在循环内改变动态。
动画摘要是:
设置您的起始变量(如动态)外您的for循环
在动画循环()中,您希望通过1次移动(不是很多移动)为画布设置动画,如下所示:
+ Increment your dynamic variable to induce motion.
+ Set your x & y to reflect the changes to dynamic.
+ Clear the canvas to prepare for this animation frame
+ Draw stuff!
循环后,使用setInterval()
如果您的动画在屏幕上运行,您也可以将其关闭!
以下是一些代码和小提琴:http://jsfiddle.net/m1erickson/fFfRS/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var c=canvas.getContext("2d");
// set the dynamic outside the loop
var dynamic = 10;
var x;
var y;
//loop function
function loop(){
// change dynamic
dynamic=dynamic*1.1;
x = dynamic;
y = dynamic*1.2;
// stop the the animation if it runs out-of-canvas
if (x>canvas.width || y>canvas.height){
c.clearRect(0,0,canvas.width,canvas.height);
clearInterval(myTimer);
alert("animation done!");
}
// clear the canvas for this loop's animation
c.clearRect(0,0,canvas.width,canvas.height);
c.fillStyle = '#87CEEB';
// draw
c.beginPath();
c.arc(x,y, 10, 0, Math.PI*2, false);
c.fill();
}
var myTimer=setInterval(loop,20);
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=400 height=400></canvas>
</body>
</html>