[英]FPS Lock for HTML Canvas/Javascript
我一直试图用我在HTML网站上制作的Spritesheet进行逐帧动画处理,但我不知道如何为动画锁定fps。 问题是它总是以闪电般的速度运行,我希望能够将它锁定为〜10-15 fps(我尝试使用Date.now()方法和setInterval方法,但它似乎不起作用)暂且。
我使用此动画的方式还依赖于检查数组,以确保它应致力于动画制作的4帧动画。 这是我一直在使用的代码。
function animateCharacter() {
var canvas = document.getElementById("portrait");
var context = canvas.getContext("2d");
var character = new Image();
character.src = "/assets/spritesheet.jpg";
animate();
function animate() {
context.drawImage(character, shift, 0, width, height, 300, 0, width / 2, height / 2);
if (currentFrame == totalFrames) {
shift = 0;
currentFrame = 0;
}
requestAnimationFrame(animate);
}
您可以尝试setTimeout
function animate(){
// do your animation
// workout your frame rate
setTimeout(animate, 500);
};
animate();
有多种方法可以解决此问题,但是通常的想法是检查rAF回调中是否包含HighResTimeStamp,并根据其更新值。
这是一个虚拟的实现,仅在至少经过一帧后才会更新,并将time_delta传递给update
函数,因此它知道应该缩放速度值多少。
const ctx = c.getContext('2d'); // we need to know when the last frame did trigger let lastTick = performance.now(); function anim(time){ const time_spent = time - lastTick, passed_frames = time_spent / (1000 / FPS.value); if(passed_frames >= 1){ update(passed_frames); lastTick = time; draw(); } requestAnimationFrame(anim); } let x = 0; const speed = 5; function update(time_delta){ x = (x + (speed * time_delta)) % (c.width - 10); } function draw(){ ctx.clearRect(0,0,c.width,c.height); ctx.fillRect(x, 50, 20, 20); } anim(performance.now());
<label>FPS: 1<input id="FPS" type="range" min="1" max="120">120</label><br> <canvas id="c"></canvas>
请注意,这只是可以完成的众多实现之一,我们还可以舍入这个time_delta值,甚至可以在for循环中运行update
,或者...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.