How To Make Snow Fall Animation

Hello , Guys today we will be demonstrating a snow fall animation with the help of html and java script.

1. HTML :

<!DOCTYPE html>
<html>
  <head>
    <title>Snowfall Animation</title>
    <style>
      canvas {
        background-color: #000;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script src="script.js"></script>
  </body>
</html>

 2. Java Script : 

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

class Snowflake {
  constructor() {
    this.x = Math.random() * canvas.width;
    this.y = -Math.random() * canvas.height;
    this.radius = Math.random() * 4 + 2;
    this.speed = Math.random() * 0.1 + 1;
    this.opacity = Math.random() * 0.5 + 0.5;
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 250, 250, ${this.opacity})`;
    ctx.fill();
  }
  update() {
    this.y += this.speed;
    if (this.y > canvas.height + this.radius) {
      this.y = -this.radius;
      this.x = Math.random() * canvas.width;
    }
  }
}

let snowflakes = [];

function createSnowflakes() {
  snowflakes = [];
  for (let i = 0; i < 50; i++) {
    snowflakes.push(new Snowflake());
  }
}

createSnowflakes();

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < snowflakes.length; i++) {
    snowflakes[i].draw();
    snowflakes[i].update();
  }
  requestAnimationFrame(animate);
}

animate();

Here you can also control the speed of snowfall and the colors and opacity of snow as well by making necessary changes in the draw() method.

The above JavaScript code defines a Snowflake class that will represent each snowflake in our animation. The draw method of this class is responsible for drawing a circle on the canvas using ctx.arc and filling it with a semi-transparent white color. The update method is responsible for updating the position of the snowflake and checking if it has reached the bottom of the canvas. If so, it repositions it to the top of the canvas.

We then create an array of Snowflake instances and draw/update them in a loop using the animate function. The requestAnimationFrame the function is used to request a new animation frame from the browser so that our animation runs smoothly.

Finally, we call the animate function to start the animation.

When you load this code in a web browser, you should see a snowfall animation with different shapes and formations. Here’s an final results.

How-To-Make-Snow-Fall-Animation
How-To-Make-Snow-Fall-Animation

Hope you guys find it helpful. Feel free to leave a comment.

Thanks for reading.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories