初始延迟的Javascript画布动画

时间:2016-03-14 15:32:44

标签: javascript animation canvas

我在画布动画中使用requestAnimationFrame,但我想在动画开始前将动画延迟3秒。我已经放了

setTimeout(draw(), 3000);

在我的代码中的许多地方。一些人在下面的代码中的注释中提到:

MyApp.prototype._animation = function() {

var cvs = document.querySelector("#animation");
var ctx = cvs.getContext("2d");

var canvasWidth = cvs.width;
var canvasHeight = cvs.height;

var requestAnimationFrame = window.requestAnimationFrame || 
                        window.mozRequestAnimationFrame || 
                        window.webkitRequestAnimationFrame || 
                        window.msRequestAnimationFrame;

var posX = 0;
var posY = 0;

// tried setTimeout here

function draw() {

  ctx.clearRect(0, 0, canvasWidth, canvasHeight);

  ctx.fillRect(100+posX,0,7,canvasHeight); //pole

  var instrument = new Path2D();
  instrument.moveTo(65+posX,50+posY);
  instrument.lineTo(100+posX,50+posY);
  instrument.lineTo(100+posX, 10+posY);
  instrument.lineTo(65+posX, 10+posY);
  instrument.arc(65+posX,30+posY, 20, Math.PI/2, 3*Math.PI/2, false);
  instrument.closePath();

  var circle = new Path2D();
  circle.arc(65+posX, 30+posY, 15, 0, 2 * Math.PI, true);

  ctx.globalCompositeOperation = "xor";

  ctx.fill(instrument);
  ctx.fill(circle);

  if (posY < 50){
      posY += 1;
  } else {
      posX += 1;
  };

  if (posX > 200) {
    return;
  }

  requestAnimationFrame(draw);

}

// tried setTimeout here
draw();

};

我想弄清楚如何在这种情况下使用setTimeout来延迟动画的开始。

编辑:我试图找出WHERE在这个方法中放置setTimeout以便最初延迟动画。

1 个答案:

答案 0 :(得分:1)

在您调用draw()的脚本底部,将其替换为:

// Note: no parens in the draw
window.setTimeout(draw,3000);
相关问题