How to Create a Bounce Animation in JavaScript?

Estimated read time 2 min read

Here’s an example of how you can create a bounce animation in JavaScript:

<html>
  <head>
    <style>
      .ball {
        width: 50px;
        height: 50px;
        background-color: red;
        border-radius: 25px;
        position: absolute;
        top: 0;
        left: 0;
      }
    </style>
  </head>
  <body>
    <div class="ball"></div>
    <script>
      const ball = document.querySelector(".ball");
      let y = 0;
      let speed = 2;
      let gravity = 0.1;
      
      function animate() {
        y += speed;
        speed += gravity;
        if (y >= 150) {
          y = 150;
          speed = -speed * 0.8;
        }
        ball.style.top = y + "px";
        requestAnimationFrame(animate);
      }
      
      animate();
    </script>
  </body>
</html>

This code creates a .ball element, and sets its initial position at the top left corner (top: 0; left: 0;). The JavaScript code defines the initial vertical position (y), speed (speed), and gravity (gravity) of the ball.

The animate function updates the y position and speed of the ball, and sets the top style of the ball element to the new y position. If the ball reaches the bottom (y >= 150), it reflects back by reversing the sign of the speed and reducing its magnitude by 20% (speed = -speed * 0.8).

The requestAnimationFrame function is used to call the animate function repeatedly, creating the animation. The requestAnimationFrame function is optimized for animation, and can ensure a smooth and efficient animation loop by syncing with the browser’s render cycle.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply