0

我正在尝试使用 for loop 和 setInterval 为画布设置动画,但到目前为止还没有运气......这是我的代码中的内容:

//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);

提前非常感谢!

4

2 回答 2

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);
于 2013-02-25T16:09:07.520 回答
1

如前所述:将您的动态移出动画循环并在循环内更改动态。

动画的总结是这样的:

  1. 在 for 循环之外设置起始变量(如动态变量)

  2. 在动画 loop() 中,您希望通过 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!
    
  3. 循环结束后,使用 setInterval() 开始动画

  4. 如果你的动画跑出屏幕,你还不如把它关掉!

这是一些代码和小提琴: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>
于 2013-02-25T16:38:35.240 回答