【发布时间】:2021-11-02 16:25:52
【问题描述】:
目前我的精灵移动得非常快。我希望放慢速度,例如降低每秒帧数。我曾尝试在各个地方使用 setInterval(),但似乎都没有。
以下是相关代码:
class Atom {
constructor(options){
this.width= 320;
this.height= 320;
this.frameX= 0;
this.frameY= 0;
this.pos= options.pos;
this.game= options.game;
this.img= new Image();
this.img.src = "sprite.png"
this.img.onload = () => this.draw()
}
draw(ctx){
drawSprite(this.img, this.width * this.frameX, this.height * this.frameY, this.width, this.height,this.pos[0], this.pos[1], this.width, this.height);
if (this.frameX < 20 ) {
this.frameX++;
} else {
this.frameX= 0;
};
}
}
function drawSprite(img, sX, sY, sW, sH, dX, dY, dW, dH) {
ctx.drawImage(img, sX, sY, sW, sH, dX, dY, dW, dH);
}
这是在我的 script.js 中运行的:
//in game.js
Game.prototype.draw= function(ctx) {
ctx.clearRect(0, 0, Game.DIM_X, Game.DIM_Y);
ctx.fillStyle = "rgba(0, 0, 0, 1)";
ctx.fillRect(0, 0, Game.DIM_X, Game.DIM_Y);
this.atom.draw(ctx);
}
// in game_view.js
GameView.prototype.start() {
this.bindKeyHandlers();
this.lastTime = 0;
// start the animation
requestAnimationFrame(this.animate.bind(this));
}
GameView.prototype.animate() {
this.game.draw(this.ctx);
requestAnimationFrame(this.animate.bind(this));
}
// finally in index.js
document.addEventListener("DOMContentLoaded", function(){
const canvas = document.getElementById('canvas');
canvas.width= Game.DIM_X;
canvas.height= Game.DIM_Y;
const ctx = canvas.getContext("2d");
const game= new Game();
game.draw(ctx);
new GameView(game, ctx).start();
})
感谢您对如何仅针对一个对象降低帧速率(因此精灵动画减慢)的任何见解。我希望避免减慢画布动画速度,以便精灵可以顺利移动。
【问题讨论】:
标签: javascript animation canvas sprite sprite-sheet