Snowfall JavaScript Code for Website

Here's a simple JavaScript code to create a snowfall effect on a webpage using HTML5 canvas and the requestAnimationFrame method:

Demo:

Code:

<style>
      canvas {
        position: fixed;
        top: 0;
        left: 0;
        pointer-events: none;
      }
    </style>
 
    <canvas id="canvas"></canvas>

    <script>
      // Initialize canvas and snowflake properties
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      var W = window.innerWidth;
      var H = window.innerHeight;
      canvas.width = W;
      canvas.height = H;

      var mp = 25; // max particles
      var particles = [];

      for (var i = 0; i < mp; i++) {
        particles.push({
          x: Math.random() * W, // x-coordinate
          y: Math.random() * H, // y-coordinate
          r: Math.random() * 4 + 1, // radius
          d: Math.random() * mp // density
        });
      }

      // Draw the snowflakes
      function draw() {
        ctx.clearRect(0, 0, W, H);

        ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
        ctx.beginPath();

        for (var i = 0; i < mp; i++) {
          var p = particles[i];
          ctx.moveTo(p.x, p.y);
          ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
        }

        ctx.fill();
        update();
      }

      // Update the snowflake positions
      var angle = 0;

      function update() {
        angle += 0.01;

        for (var i = 0; i < mp; i++) {
          var p = particles[i];
          p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
          p.x += Math.sin(angle) * 2;

          if (p.x > W + 5 || p.x < -5 || p.y > H) {
            if (i % 3 > 0) {
              particles[i] = {
                x: Math.random() * W,
                y: -10,
                r: p.r,
                d: p.d
              };
            } else {
              if (Math.sin(angle) > 0) {
                particles[i] = {
                  x: -5,
                  y: Math.random() * H,
                  r: p.r,
                  d: p.d
                };
              } else {
                particles[i] = {
                  x: W + 5,
                  y: Math.random() * H,
                  r: p.r,
                  d: p.d
                };
              }
            }
          }
        }
      }

      // Animation loop
      function loop() {
        requestAnimationFrame(loop);
        draw();
      }

      loop();
</script>

You can copy and paste this code into an HTML file and open it in your web browser to see the snowfall effect. Note that you can adjust the mp variable to change the number of snowflakes on the page.

Next Post Previous Post
No Comment
Add Comment
comment url