DEV Community

Anonymous!
Anonymous!

Posted on

3

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>.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay