DEV Community

Anonymous!
Anonymous!

Posted on

Pure SVG color change animation

A first SVG animation, using the animate tag to change between several different colors.

1. Create the SVG shape.

This one is just a square <rect> 100 pixels long, with a color fill of blue #0000ff and a stroke color black #000000.

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
 <rect x="0" y="0" height="100" width="100" fill="#0000ff" stroke="#000000">
 </rect>
</svg>

2. Add the animate code

Add the animate tag inside the square's <rect>to flash between multiple colors using hex color codes held in values (#00ff00 green, #ff00ff purple, #ff0000 red) and the timings for each is held by keyTimes. The values in keyTimes must be between 0 and 1.

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
 <rect x="0" y="0" height="100" width="100" fill="#0000ff" stroke="#000000">
 <animate
 attributeName="fill"
 attributeType="XML"
 keyTimes="0; 0.5; 1"
 begin="0s" dur="5s" values="#00ff00;#ff00ff;#ff0000"
 calcMode="discrete"
 repeatCount="indefinite"/>
 </rect>
</svg>

3. Run it

You can also embed it within a HTML document, eg in the <body> tag or a <div>.

Top comments (0)