Custom SVG progress bar fill

3.3k views Asked by At

In its simplest form, I want to make a loading page like this website.

I want to use a custom SVG logo (that I have made in illustrator) and horizontally fill the logo as the page loads.

Like a SVG clip mask progress bar (or something).

Please, please help me!

Thanks, Jon

1

There are 1 answers

15
Paul LeBeau On

The simplest way to do this is with a gradient fill.

<linearGradient id="progress">
   <stop id="stop1" offset="0" stop-color="black"/>
   <stop id="stop2" offset="0" stop-color="grey"/>
</linearGradient>

You just need to change the value of offset on both <stop> elements to be the percentage you want - either 0->1 or "0%"->"100%". For example:

An example function might be:

function setProgress(amt)
{
  amt = (amt < 0) ? 0 : (amt > 1) ? 1 : amt;
  document.getElementById("stop1").setAttribute("offset", amt);
  document.getElementById("stop2").setAttribute("offset", amt);
}

This approach works for any SVG element, whether it be text, as in the demo below, or a complicated logo made of paths.

function setProgress(amt)
{
  amt = (amt < 0) ? 0 : (amt > 1) ? 1 : amt;
  document.getElementById("stop1").setAttribute("offset", amt);
  document.getElementById("stop2").setAttribute("offset", amt);
}

  
// Simple test of setProgress().
// We step up from 0 to 1 using timeouts
val = 0;
doTimeout();

function doTimeout() {
  setProgress(val);
  val += 0.01;
  if (val <= 1) {
    setTimeout(doTimeout, 30);
  }
}
text {
  font: 'Times Roman', serif;
  font-size: 125px;
  fill: url(#progress);
}
<svg width="650" height="150">
  <defs>
    <linearGradient id="progress">
      <stop id="stop1" offset="0" stop-color="black"/>
      <stop id="stop2" offset="0" stop-color="grey"/>
    </linearGradient>
  </defs>

  <text x="20" y="120">TILL JANZ</text>
</svg>