背景如何每n秒变化一次?

时间:2018-01-04 04:56:41

标签: javascript

请求动画帧功能,更快地更新画布,所以,我不能做我想要的。我想要什么 ?我想每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);
&#13;
<canvas></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题是,您正在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>