背景如何每 n 秒变化一次



>he requestAnimationFrame函数,更新画布太快,所以,我不能做我想做的事。我想要什么?我想每 2 秒更改一次画布的背景颜色,但问题是我在每一帧中都清理画布。我能做什么?

(function(d, w) {
    var canvas = d.getElementsByTagName("CANVAS")[0],
        ctx = canvas.getContext("2d");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    var x = 0,
        y = 0,
        speedX = .9;
    update(x, y, speedX);
    function update(x, y, speedX) {
        var color = "";
        setTimeout(function() { // Here i try set the color each 2s
            color = randomColor(); // Need the color here
        }, 2000);
        ctx.fillStyle = color; // here paint the background
        ctx.fillRect(0, 0, canvas.width, canvas.height); // paint
        x += speedX;
        box(x, y, speedX);
        requestAnimationFrame(function() { // animation frame
            update(x, y, speedX);
        });
    }
    function box(x, y, speedX) {
        ctx.fillStyle = "Black";
        ctx.fillRect(+x, +y, 50, 50);
        ctx.stroke();
    }
    function randomColor() {
        for (var i = 0, str = "", hex = "0123456789ABCDEF",
                random, max = hex.length; i < 6; i++, random =
            Math.floor(Math.random() * max), str += hex[random]);
        return "#" + str;
    }
})(document, window);
<canvas></canvas>

问题是,您正在初始化每秒触发color update超时。因此,从本质上讲,您每毫秒创建一个新的超时,但此值永远不会被接受,因为更新color时,您将其值重置为 "" .将代码移动到外部以更改背景并改用setInterval。因此,创建计时器和更新颜色的过程是单独的部分,您不会在递归中覆盖它。

下面是一个示例

(function(d, w) {
  var canvas = d.getElementsByTagName("CANVAS")[0],
    ctx = canvas.getContext("2d");
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  var x = 0,
    y = 0,
    speedX = .9;
  update(x, y, speedX);
  var color = randomColor();
  setInterval(function() { // Here i try set the color each 2s
    color = randomColor(); // Need the color here
  }, 2000);
  function update(x, y, speedX) {
    requestAnimationFrame(function() { // animation frame
      ctx.fillStyle = color; // here paint the background
      ctx.fillRect(0, 0, canvas.width, canvas.height); // paint
      x += speedX;
      box(x, y, speedX);
      update(x, y, speedX);
    });
  }
  function box(x, y, speedX) {
    ctx.fillStyle = "Black";
    ctx.fillRect(+x, +y, 50, 50);
    ctx.stroke();
  }
  function randomColor() {
    for (var i = 0, str = "", hex = "0123456789ABCDEF",
        random, max = hex.length; i < 6; i++, random =
      Math.floor(Math.random() * max), str += hex[random]);
    return "#" + str;
  }
})(document, window);
<canvas></canvas>

相关内容

最新更新