Holi Festival Effect JavaScript Code for Website

Here's a simple JavaScript code to create a colorful Holi festival 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 particle 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 = 50; // 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() * 10 + 5, // radius
          c: 'hsla(' + (Math.random() * 360) + ', 80%, 50%, 0.8)' // color
        });
      }

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

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

        update();
      }

      // Update the particle positions
      function update() {
        for (var i = 0; i < mp; i++) {
          var p = particles[i];
          p.y += Math.random() * 2 + 1;
          p.x += Math.random() * 2 - 1;

          if (p.x > W + 5 || p.x < -5 || p.y > H) {
            particles[i] = {
              x: Math.random() * W,
              y: -10,
              r: p.r,
              c: p.c
            };
          }
        }
      }

      // 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 colorful Holi festival effect. Note that you can adjust the mp variable to change the number of particles on the page. The color of each particle is randomly generated using the h

Next Post Previous Post
No Comment
Add Comment
comment url