0

我有一个我应该编写的小程序,它可以在画布上制作一个弹力球。我可以得到一个球弹跳的线框,但似乎根本无法触发 setTimeout。我已经阅读,阅读并阅读了有关该功能的信息,但无法弄清楚(新)。

<!DOCTYPE HTML>
<html>
   <head>
      <title>basic Canvas</title>
      <style>
         #canvas1{
            border:1px solid #9C9898;
         }
         body{
            margin:0px;
            padding:0px;
        }
      </style>
      <script>
         function drawMe(){
            //Set x,y,radius
            var x = 60;
            var y = 60;
            var radius = 70;
            drawLoop(x,y,radius);
         }

         function drawLoop(x,y,radius){
            var canvas2=document.getElementById("canvas1");
            var ctx=canvas2.getContext("2d");
            for(i=1;i<100;i++){

                    if(y + radius >= canvas2.height){
                        d = 1;
                    }
                    if(y - radius <= 0){
                        d = 0;
                    }
                    if (d==0){
                        x = x + 10;
                        y = y + 10;
                    }
                    else if (d==1){
                        x = x + 10;
                        y = y - 10;
                    }
                    draw(x,y,radius);
                    window.setTimeout(function() {draw(x,y,radius)},3000);
                }
         }

         function draw(x,y,radius){
                    var canvas2=document.getElementById("canvas1");
                    var ctx=canvas2.getContext("2d");

                    ctx.beginPath();
                    ctx.arc(x,y,radius,0,2*Math.PI,false);
                    var gradient = ctx.createRadialGradient(x, y, 1, x, y, radius);
                    gradient.addColorStop(0,"blue");
                    gradient.addColorStop(1,"white");
                    ctx.fillStyle=gradient;
                    ctx.lineWidth=1;
                    ctx.strokeStyle="blue";
                    ctx.fill();
                    ctx.stroke();
         }
      </script>
   </head>
   <body onload="drawMe()">
      <canvas id="canvas1" width=1000" height="400">

      </canvas>
   </body>
</html>

一个名为“drawMe()”的小函数设置 x、y 和半径,然后调用一个小绘图循环,该循环触发 100 次以绘制弹力球(“drawLoop”)。在函数drawLoop的底部,我调用draw,它实际上绘制了圆圈。根据我的阅读,'setTimeout(function(){draw(x,y,radius)};,3000); 应该每三秒调用一次绘图函数。但事实并非如此。我到底做错了什么?

4

1 回答 1

3

setTimeouts are counted from the time they are created. The loop runs almost instantly and creates the setTimeouts at almost the same time. They are then all ran 3 seconds later.

One way to get around this is in the solution below. This does not increment the loop until the current timeout has been completed. http://jsfiddle.net/x8PWg/14/

This is only one of the many potential solutions to this.

于 2012-10-11T20:53:15.163 回答