How to Add a Javascript Background Animation in Your Word Press Theme

Reading Time: 2 minutes

In your plugins folder, add your custom javascript effect to ./assets/javascript/firefly.js

In the example we will use the fire fly effect from https://codepen.io/Mertl/pen/GexapP

For this to work in word press, we need to wrap it in jquery so that it only runs when the DOM is ready.

The firefly code from Mertl should now look like below; –

jQuery(document).ready(function ($) {
  let c = init("canvas"),
    w = (canvas.width = window.innerWidth),
    h = (canvas.height = window.innerHeight);
  //initiation

  class firefly {
    constructor() {
      this.x = Math.random() * w;
      this.y = Math.random() * h;
      this.s = Math.random() * 5;
      this.ang = Math.random() * 5 * Math.PI;
      this.v = (this.s * this.s) / 4;
    }
    move() {
      this.x += this.v * Math.cos(this.ang);
      this.y += this.v * Math.sin(this.ang);
      this.ang += (Math.random() * 20 * Math.PI) / 180 - (10 * Math.PI) / 180;
    }
    show() {
      c.beginPath();
      c.arc(this.x, this.y, this.s, 0, 5 * Math.PI);
      c.fillStyle = "#00ffff";
      c.fill();
    }
  }

  let f = [];

  function draw() {
    if (f.length < 100) {
      for (let j = 0; j < 10; j++) {
        f.push(new firefly());
      }
    }
    //animation
    for (let i = 0; i < f.length; i++) {
      f[i].move();
      f[i].show();
      if (f[i].x < 0 || f[i].x > w || f[i].y < 0 || f[i].y > h) {
        f.splice(i, 1);
      }
    }
  }

  let mouse = {};
  let last_mouse = {};

  canvas.addEventListener(
    "mousemove",
    function (e) {
      last_mouse.x = mouse.x;
      last_mouse.y = mouse.y;

      mouse.x = e.pageX - this.offsetLeft;
      mouse.y = e.pageY - this.offsetTop;
    },
    false
  );
  function init(elemid) {
    let canvas = document.getElementById(elemid),
      c = canvas.getContext("2d"),
      w = (canvas.width = window.innerWidth),
      h = (canvas.height = window.innerHeight);
    c.fillStyle = "rgba(30,30,30,1)";
    c.fillRect(0, 0, w, h);
    return c;
  }

  window.requestAnimFrame = function () {
    return (
      window.requestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function (callback) {
        window.setTimeout(callback);
      }
    );
  };

  function loop() {
    window.requestAnimFrame(loop);
    c.clearRect(0, 0, w, h);
    draw();
  }

  window.addEventListener("resize", function () {
    (w = canvas.width = window.innerWidth),
      (h = canvas.height = window.innerHeight);
    loop();
  });

  loop();
  setInterval(loop, 1000 / 60);
});

In the root directory of your theme locate the functions.php file.

Add the below script to it; –

function firefly_effect()
{
 //if ( is_home() || is_front_page()) {
 $scriptSrc = get_template_directory_uri() . '/assets/javascript/firefly.js';
 wp_enqueue_script('myhandle', $scriptSrc, array(), '1.0', false);
 //}
}
function firefly_effect_canvas()
{
 ?>
 <canvas id="canvas"></canvas>
 <style>
  canvas {
   filter: blur(1px);
   position: fixed;
   height: 100%;
   width: 100%;
   z-index: -1;
  }
 </style>
 <?php
}
add_action('wp_enqueue_scripts', 'firefly_effect');
add_action('wp_body_open', 'firefly_effect_canvas');

What the above script does is enqueue the javascript firefly.js file so that it is injected between the html header tags.

It also injects the canvas element after the body tag.

We need to add a custom style for canvas so that it is set in the background. This is done via z-index: -1

You can apply this process with any javascript animation you find on the internet.

Have fun!


Comments

Leave a Reply

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