JavaScript中的动画坐标-预先计算的值与即时计算

我正在使用JavaScript和HTML5 <canvas>制作循环动画。动画包括使用canvas的lineTo()方法在10到200个坐标之间建立动画形状。动画正在循环播放,持续时间为10到20秒。我使用requestAnimationFrame()来查看大约60fps,每次迭代的每个坐标的位置都会更新。

处理这种类型的动画最有效的方法是什么?

方法1-动态计算

当前,我只是在计算和更新requestAnimationFrame()的每次迭代中每个点的位置。性能还可以,但是在较旧的设备上,我注意到CPU使用率激增,偶尔出现渲染滞后。这些计算是非常基本的几何操作。

方法2-预先计算的职位

我一直在想预先计算一个点可能具有的每个可能位置,并将其存储在内存中的想法。然后,在requestAnimationFrame()循环中,我可以简单地访问每个点的坐标并更新其位置。但是我不确定性能影响以及它是否真的会产生影响。

我计划测试方法2,以查看是否存在明显差异。但是我很好奇是否应该考虑另一种方法?画布在这里是工作的正确选择吗?还是我应该看WebGL之类的东西?

***编辑:这是计算和画布绘制功能,因此您可以了解在每个帧上运行的计算:

Animation.prototype = {

  ... the rest of the prototype setup ...

  // This function runs once per `requestAnmiationFrame()` call:
  updateNodes: function() {
    let progress = this.getProgressRadians(); // simple time offset

    // This loops over between 10-200 node objects,updating their positions
    this.nodes.forEach(node => {
      let offset =
        ((Math.sin(progress - node.numberOffset) + 1) / 2) *
        this.pixelWaveHeight;

      if (this.waveGrows) {
        offset =
          offset * (node.index / (this.nodes.length - 1)) * this.waveGrows;
      }

      if (this.waveAngleRadians) {
        offset +=
          Math.tan(this.waveAngleRadians) * this.spaceBetweenNodes * node.index;
      }

      let yValue = this.canvas.height - offset - this.pixelBaseHeight;

      node.y = yValue;
    });
  },// This function runs at the end of each `requestAnimationFrame()` call
  draw: function() {
    let ctx = this.canvas.ctx;
    ctx.clearRect(0,this.canvas.width,this.canvas.height);
    ctx.beginPath();
    ctx.moveTo(0,this.canvas.height);
    this.nodes.forEach(node => {
      ctx.lineTo(node.x,node.y);
    });
    ctx.lineTo(this.canvas.width,this.canvas.height);
    ctx.lineTo(0,this.canvas.height);
    ctx.closePath();
    ctx.fill();
  }
}

大多数这些属性都是静态的,例如首先计算一次,然后访问: pixelWaveHeight-数字 waveGrows-数字

SKYyang0782 回答:JavaScript中的动画坐标-预先计算的值与即时计算

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3098650.html

大家都在问