Как я могу иметь несколько одновременных анимаций на 1 холсте в JavaScript

1

Я использую спрайты для анимации 3 разных персонажей. Но проблема, которую я получаю, я вижу только одну из трех анимаций (я думаю, тот, который загружается быстрее других). Есть ли способ оживить их в одно и то же время, чтобы все их можно было увидеть?

ЯШ:

var monsterImg = new Image();
var monsterImg1 = new Image();
var monsterImg2 = new Image();

var canvas = document.getElementById("board");

monsterImg1.src = "minotaur.png";
monsterImg.src = "manyeyedball.png";
monsterImg2.src = "nomad.png";

var monster = sprite({
    context: canvas.getContext("2d"),
    width: 936,
    height: 222,
    image: monsterImg,
    x: 0,
    y: 144,
    amp: 10
});

var monster1 = sprite({
    context: canvas.getContext("2d"),
    width: 540,
    height: 144,
    image: monsterImg1,
    x: 0,
    y: 0,
    amp: 10
});

var monster2 = sprite({
    context: canvas.getContext("2d"),
    width: 828,
    height: 114,
    image: monsterImg2,
    x: 0,
    y: 366,
    amp: 15
});

function sprite (options) {

    var that = {},
        frameIndex = 0,
        tickCount = 0,
        ticksPerFrame = options.ticksPerFrame || 4,
        numberOfFrames = options.numberOfFrames || 6;

    that.context = options.context;
    that.width = options.width;
    that.height = options.height;
    that.image = options.image;
    that.x = options.x;
    that.y = options.y;

    that.loop = options.loop;

    that.update = function () {

        tickCount += 1;

        //console.log("tick count: " + tickCount);

        if (tickCount > ticksPerFrame) {

            tickCount = 0;

            //console.log("frame index: " + frameIndex + ", number of frames: " + numberOfFrames)

            // If the current frame index is in range
            if (frameIndex < numberOfFrames - 1) {  
                // Go to the next frame
                frameIndex += 1;
                that.x += options.amp;
            }
            else {
                frameIndex = 0;
            }
            //console.log("frame index: " + frameIndex);
        }
    };

    that.render = function () {

        // Clear the canvas
        that.context.clearRect(0, 0, canvas.width, canvas.height);

        // Draw the animation
        that.context.drawImage( that.image, frameIndex * that.width / numberOfFrames, 0, that.width / numberOfFrames, that.height, that.x, that.y, that.width / numberOfFrames, that.height);
    };

    return that;
}

function eyedBallLoop() {

    window.requestAnimationFrame(eyedBallLoop);

    monster.update();
    monster.render();
}

function minotaurLoop() {

    window.requestAnimationFrame(minotaurLoop);

    monster1.update();
    monster1.render();
}

function nomadLoop() {

    window.requestAnimationFrame(nomadLoop);

    monster2.update();
    monster2.render();
}

monsterImg.addEventListener("load", eyedBallLoop, false);
monsterImg1.addEventListener("load", minotaurLoop, false);
monsterImg2.addEventListener("load", nomadLoop, false);

HTML:

<!DOCTYPE HTML>
<html>
    <body>
        <canvas id="board" width="950" height="950"></canvas>

        <script type="text/javascript" src="test.js"></script>
    </body>

изображений:

1-й: https://imgur.com/o9hC5d8

2nd: https://imgur.com/I4SY0c9

3-й: https://imgur.com/3nM3lmT

Теги:
canvas
drawing
animation
requestanimationframe

1 ответ

1
Лучший ответ

Проблема в том, что вы очищаете полотно перед каждым рендером в функции sprite.
Вместо этого сделайте все три изображения и очистите полотно перед каждым раундом рендеринга.
Еще одна вещь, которую следует учитывать, - это визуализировать каждый из них каждый раз, когда вы получаете рамку анимации. Просто перебирайте массив "монстров".

Ещё вопросы

Сообщество Overcoder
Наверх
Меню