Successfully!

Error!

JS Create a Dynamic Wave Background

  • Last update:  2020-12-30
  • I. Overview

    Create a cool dynamic wave background for a dashboard, as shown in the following figure:

    1.gif

    II. Example

    2.1 Add  event

    Click the body and add a Post Initialization event, as shown in the following figure:

    image.png

    The JS code is as follows:

    $("body").prepend('<canvas id="canvas" style="position:absolute;z-index:-2;"></canvas>');
    //Insert the canvas into the body and place it at the bottom
    var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      canvas.width = canvas.parentNode.offsetWidth;
      canvas.height = canvas.parentNode.offsetHeight;
      //If the browser supports requestAnimFrame, use requestAnimFrame otherwise use setTimeout
      window.requestAnimFrame = (function(){
      return window.requestAnimationFrame ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame ||
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
      })();
      //The initial angle is 0
      var step = 0;
      //Define the colors of three waves
      var lines = ["rgba(0,222,255, 0.2)",
                     "rgba(157,192,249, 0.2)",
                     "rgba(0,168,255, 0.2)"];
      function loop(){
          ctx.clearRect(0,0,canvas.width,canvas.height);
          step++;
          //Draw 3 rectangles with different colors
          for(var j = lines.length-1; j >= 0; j--) {
              ctx.fillStyle = lines[j];
              //The angle of each rectangle is different, the difference between each is 45 degrees
              var angle = (step+j*45)*Math.PI/180;
              var deltaHeight = Math.sin(angle) * 50;
              var deltaHeightRight = Math.cos(angle) * 50;
              ctx.beginPath();-
              ctx.moveTo(0, canvas.height/2+deltaHeight);
              ctx.bezierCurveTo(canvas.width /2, canvas.height/2+deltaHeight-50, canvas.width / 2, canvas.height/2+deltaHeightRight-50, canvas.width, canvas.height/2+deltaHeightRight);
              ctx.lineTo(canvas.width, canvas.height);
              ctx.lineTo(0, canvas.height);
              ctx.lineTo(0, canvas.height/2+deltaHeight);
              ctx.closePath();
              ctx.fill();
          }
          requestAnimFrame(loop);
      }
      loop();


    2.2 Effect preview

    The effect is shown at the beginning.

    III. Completed Template

    Attachment List


    Theme: Dashboard
    Already the First
    Already the Last
    • Helpful
    • Not helpful
    • Only read

    Doc Feedback