interwebjill
interwebjill

Reputation: 950

Javascript canvas animation with initial delay

I am using requestAnimationFrame in my canvas animation, but I would like to delay the animation for 3 seconds before it starts. I have placed

setTimeout(draw(), 3000);

in many places in my code. Some noted in the comments in the code below:

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

};

I am trying to figure out how to use setTimeout in this case in order to delay the start of the animation.

EDIT: I am trying to figure out WHERE to place setTimeout in this method in order to initially delay the animation.

Upvotes: 0

Views: 404

Answers (1)

markE
markE

Reputation: 105015

At the bottom of your script where you call draw(), replace that with:

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

Upvotes: 1

Related Questions