画布动画持续时间(按时间表示)



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

这个想法是计算帧之间的毫秒数,将其除以 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>

您应该计算增量时间(每帧之间的时间(以毫秒为单位的时间)。这可以像@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();
<script src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>

最新更新