【问题标题】:How do I slowdown my sprite animation in JavaScript Canvas?如何在 JavaScript Canvas 中减慢我的精灵动画?
【发布时间】: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


    【解决方案1】:

    我找到了解决方案:

    //in class Atom constructor:
    this.counter = 3;
    
    //in class Atom's draw(ctx) function:
    if (this.counter > 0){
                this.counter -=1;
            } else {
                if (this.frameX < 20 ) {
                    this.frameX++;
                } else {
                    this.frameX= 0;
                };
                this.counter = 3
            }

    希望这能为您节省一些时间,疲惫的旅行者。

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 2016-04-26
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多