skip to Main Content

Im now doing project Google Dino, and I want to make a random cactus animation time and delay but I dont know how, here is my code:

`.cactus-anim {
    animation: cactus-move 1.3s 0.5s linear infinite;

}

@keyframes cactus-move {
    0% {
        left: 700px;
    }

    100% {
        left: -40px;
    }
}`

(I want to make instead of 1.3s – random(1-2)s, and instead of 0.5s – random(0-0.7)s , and also Im using Scss and Js, Thnks

2

Answers


  1. You could add this code to your JS, and run it whenever you need to randomize the animation time, but this is not possible in plain CSS.

    const anim = document.querySelector(".cactus-anim");
    
    // gets a random number between 2 values
    function randNum(min, max) {
        return Math.random() * (max - min) + min
    }
    
    // run this function to set a new, random animation time
    function randAnimTime() {
        // sets the new animation time
        // first time random is between 1 and 2 seconds
        // second is random between 0 and 0.7 seconds
        anim.style.animation = "cactus-move " + randNum(1, 2) + "s " + randNum(0, 0.7) + "s linear infinite";
    }
    
    Login or Signup to reply.
  2. CSS

    .cactus-anim {
        animation: cactus-move var(--animation-duration) var(--animation-delay) linear infinite;
    }
    
    @keyframes cactus-move {
        0% {
            left: 700px;
        }
    
        100% {
            left: -40px;
        }
    }
    

    Javs Script:

    const elements = document.querySelectorAll('.cactus-anim');
    
    
    elements.forEach((element) => {
      // Generate random animation duration between 0.5s and 2s
      const duration = Math.random() * 1.5 + 0.5;
      element.style.setProperty('--animation-duration', `${duration}s`);
    
      // Generate random animation delay between 0s and 1s
      const delay = Math.random();
      element.style.setProperty('--animation-delay', `${delay}s`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search