Home > Software engineering >  How to trigger paused animation with javascript?
How to trigger paused animation with javascript?

Time:10-04

I want to trigger an animation that makes the game screen fade to greyscale when the character dies. This is my first game so it is rather simple. I have not been able to successfully trigger the animation. I have not been able to successfully trigger the animation. Online, I found that document.getElementById("object").animationPlayState = "running" should work, but it doesn't. This is my game loop and CSS (game is a <div> in HTML).

link to full code in codepen (doesn't work properly): https://codepen.io/flyingchicken22/pen/NWgVrJq

CSS:

#game {
    width: 600px;
    height: 300px;
    border: 2px solid black;
    margin: auto;
    background-image: url("https://t3.ftcdn.net/jpg/01/73/79/26/360_F_173792623_516juhwjkCCZJ9OyesyH7hf7r9zsyH5u.jpg");
    background-size: cover;
    animation: deathAnimation 2s;
    animation-play-state: paused;
}

@keyframes deathAnimation {
    0%{filter:none;}
    100%{filter:grayscale(100%);}
}

Javascript:

var gameLoop = setInterval(() => {
    dead = false
    function rockAnimation() {
        rock.classList.add('rockAnimation')
    }
    const knightTop = parseInt(window.getComputedStyle(knight).getPropertyValue('top'))
    const rockLeft = parseInt(window.getComputedStyle(rock).getPropertyValue('left'))
    if (rockLeft < 0) {
        rock.style.display = 'none'
    } else {
        rock.style.display = ''
    }

    if (rockLeft < 90 && rockLeft > 50 && knightTop > 79) {
        dead = true
    }
    score.innerText  

    const deathAnimation = document.getElementById("deathAnimation")
    const game = document.getElementById("game")
    if (dead == true) {
        clearInterval(gameLoop)
        document.getElementById("youDied").innerHTML = "YOU DIED"
        document.getElementById("playAgain").innerHTML = "Play Again?" 
        game.classList.add(deathAnimation)
        document.getElementById("deathAnimation").style.animationPlayState = "running"
    }
}, 50);

CodePudding user response:

You are trying to return an HTML element that does not exist. Change document.getElementById("deathAnimation").style.animationPlayState = "running" to document.getElementById("game").style.animationPlayState = "running"

Try the following snippet

  • Related