【问题标题】:canvas animation duration in time画布动画持续时间
【发布时间】:2018-06-15 06:35:33
【问题描述】:

在 HTML 画布中,我们希望 fps 是动态的,并且不要让我们使用的用户设备崩溃 requestAnimationFrame() 但我让画布动画的 fps 保持动态并以秒为单位测量动画的持续时间30fps 的动画会在 60fps 完成的同时完成吗?

【问题讨论】:

  • 使用getMilliseconds 测量帧之间的时间并将其相应地纳入动画。另外:stackoverflow.com/questions/9715867/…
  • 谁可以这样做?我知道您从我绘制的画布元素的其中一种尺寸中添加或删除动画速度的任何帧
  • requestAnimationFrame 回调的第一个参数是高精度时间戳(毫秒) - 使用它来计算调用之间传递的时间并相应地为动画计时。
  • tnx 帮忙,但你能给我一个示例代码,我会更了解你,因为我真的不知道谁来测量帧之间的时间

标签: javascript html animation html5-canvas


【解决方案1】:

这个想法是计算帧之间的毫秒数,将其除以 1000,然后将结果乘以以像素每秒为单位的速度。

这是使用传递给requestAnimationFrame的计时参数的示例代码:

var $square;
var x = 0;
var speed = 100; // pixels per second

var prevTime; // start as undefined to prevent jumping

function tick(now) {
  // schedule next tick
  requestAnimationFrame(tick);
  // calculate factor
  delta = (now - prevTime) / 1000;
  prevTime = now;
  if (isNaN(delta)) return; // skip very first delta to prevent jumping

  x += speed * delta;
  $square.css({
    left: x
  });
}

$(document).ready(function () {
  $square = $("#square");
  requestAnimationFrame(tick);
});
body {
  margin: 15px;
  border: 1px solid black;
  width: 500px;
  position: relative;
  line-height: 30px;
}

#square {
  width: 30px;
  height: 30px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
  border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
500 pixels in five seconds
<div id="square"></div>

【讨论】:

    【解决方案2】:

    您应该计算增量时间(每帧之间的时间以毫秒为单位)。这可以像@Chris G 所做的那样完成。如果您想轻松获得帧之间的增量时间并在 画布 上绘制移动对象,最简单的方法是使用诸如 Canvas.js 之类的库:

    const canvas = new Canvas('my-canvas', 500, 500);
    
    canvas.on('start', function ( ctx, handyObject ) {
    
      handyObject.Ball = {
        x: 10,
        y: 10,
        speed: 100 // Pixels per second
      };
      
    });
    
    canvas.on('update', function (handyObject, delta) {
    
      handyObject.Ball.x += handyObject.Ball.speed * delta; // The magic happens. The speed is multiplied with the delta which often is around 0.016. Delta time is the time since the ball was last updated. Using delta time will make sure the ball moves exactly the same no matter what framerate the client is running.
      
    });
    
    canvas.on('draw', function (ctx, handyObject, delta) {
    
      ctx.clear();
    
      ctx.beginPath();
      
      ctx.arc(handyObject.Ball.x, handyObject.Ball.y, 10, 0, 2 * Math.PI);
      
      ctx.fill();
      
    });
    
    canvas.start();
    &lt;script src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"&gt;&lt;/script&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2012-12-12
      • 1970-01-01
      • 2013-01-18
      相关资源
      最近更新 更多