【问题标题】:Javascript canvas animation with initial delay带有初始延迟的 Javascript 画布动画
【发布时间】:2016-03-15 02:03:00
【问题描述】:

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

setTimeout(draw(), 3000);

在我的代码中的许多地方。一些在下面代码中的 cmets 中注明:

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 来延迟动画的开始。

编辑:我试图找出在此方法中放置 setTimeout 的位置,以便最初延迟动画。

【问题讨论】:

  • setTimeout(draw, 3000);setTimeout(function() { draw() }, 3000);
  • 我将使用它,但我想知道将它放在方法中的哪个位置。
  • 它应该在那里工作。虽然你需要等待文件被加载。
  • $(function() { //你所有的代码都在这里 });哪个是 document.onload 的 jQuery 快捷方式
  • 它在我的代码中指示的那两个地方不起作用。此外,当文档到达代码中的这个位置时,肯定会加载文档。

标签: javascript animation canvas


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多