在HTML画布中,我们希望fps是动态的,不要让用户设备崩溃我们正在使用requestAnimationFrame()
但是我保持画布动画的fps动态并测量持续时间30fps动画在60fps完成的同时完成的动画(以秒为单位)?
答案 0 :(得分:0)
想法是计算帧之间的毫秒数,除以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>
&#13;
答案 1 :(得分:0)
您应该计算增量时间(每帧之间的时间,以毫秒为单位)。这可以像@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>