Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a percentage of an SVG and animate the fill

Tags:

html

css

svg

Currently, I am working on a project that is comparing state data with data from another country. One data point is percentage of protected land and I want to fill the a percentage of the state that matches the data point. So for example, if 25% of North Carolina is protected, then I want 25% of the state to fill. Currently, I am trying to use an svg and I want the fill to happen on page load.

Any suggestions or resources on how to do this would be greatly appreciated.

Example I drew up in Illustrator:

NC filled in 33%

like image 653
hi_Matt Avatar asked Apr 08 '13 18:04

hi_Matt


People also ask

Can you animate fill SVG?

Animating fill requires SVG elements instead of CSS: linearGradient allows us to define multiple colors to fill a shape. Yes, a gradient.

How to fill a SVG?

The fill is the color inside a shape, and the stroke is the visible outline of an object. You can fill a shape with one color and stroke it with another. If you create an SVG shape but don't set the fill color, the shape will be colored in black.


2 Answers

Here are my two cents:

You can have a linear gradient like this:

<linearGradient y2="0%" x2="100%" y1="0%" x1="0%" id="F1g"><stop stop-color="#00FF00" offset="0%" id="F1gst1"/><stop stop-color="#FFFFFF" offset="0%" id="F1gst2"/></linearGradient>

Then take the first stop element:

var firstStop = document.getElementById('F1gst1');

And then assign the percentage you want fill, with the attribute offset:

percentage = '35%'; firstStop.setAttribute('offset',percentage);

And that is the way in javascript. You need a gradient for every state (you can use a group) and maybe you will need to define a path object with a fill inside every state with the same form, so you can apply the linear gradient to that path fill attribute.

If you need an animation, you can set a setInterval, and add an '1%' every x miliseconds to make the effect, and stop every interval when the desired percentage is reached.

I hope this at least have given you a clue.

Regards.

like image 70
Chatyeux Avatar answered Sep 29 '22 03:09

Chatyeux


This can be done by plain css and html: http://jsfiddle.net/haohcraft/rAPN5/1/

Basically, the trick is

  1. You need a image which has a transparent inner field but non-transparent outer field, like the image in the fiddle. And you need to set z-index:1 in order to place it above the filled <div>.
  2. Set the filled <div> and the img to be position: absolute; width:90px; height:90px; in that case.
  3. Then you can adjust the height of the filled div to show the percentage
like image 33
Hao Avatar answered Sep 29 '22 04:09

Hao