press any key or tap to skip

>vs slavchev's cyberspace

Animating SVG with simple JS

animation website

A nice looking effect can be achieved by gradually drawing a SVG. You can do this for an icon or some text that is made out of paths.

SVG files are just XML so you can use a SVG editor to make the paths and open the file with a text editor. When copying the tags to your HTML you should check if the code is also valid HTML, maybe you need to close the tags or delete some attributes.

You can fit this to your needs by having it also draw backwards by reducing the length that is overwritten each tick on the strokeDasharray. You can have this run when the page opens or an element is hovered or a menu text/icon is rendered.

/* original idea from: https://stackoverflow.com/a/14282391 by https://stackoverflow.com/users/405017/phrogz */

var percentageChangePerTick = 0.01;
var drawFPS = 60;

var paths = document.querySelectorAll('path.animatable');
var timer;

function startDrawingPath(){
  for (var i = 0; i < paths.length; i++) {
    paths[i].style.stroke = '#00FF66';
    paths[i].style.strokeDasharray = 0;
  }
  clearInterval(timer);
  increaseLength();
  timer = setInterval(increaseLength,1000/drawFPS);
}

function increaseLength(){
  var finished = true;
  for (var i = 0; i < paths.length; i++) {
    var totalPathLength = paths[i].getTotalLength();
    var currentLength = parseFloat(paths[i].style.strokeDasharray.split(",")[0]);
    var newLength = currentLength + (percentageChangePerTick * totalPathLength);
    paths[i].style.strokeDasharray = [newLength, totalPathLength].join(' ');
    if (newLength <= totalPathLength) {
      finished = false;
    }
  }
  if (finished) {
    clearInterval(timer);
  }
}