Animating SVG Paths







You’ve seen SVG paths, right?

<path d='M 0 2 L 0 0' />

The d attribute defines a series of path commands that are used to draw a path. When I was looking at the MDN page for the format to write a small SVG by hand, I noticed this:

d is a presentation attribute, and hence can also be used as a CSS property.

When I read that, one of the first things that came to mind was whether or not this can be used to animate SVG paths. And, amazingly, the answer is yes!

Here’s an example, adapted from the MV editor I’ve been working on:

<svg
	viewBox='-1.5 -0.5 3 3'
	height='96' width='96'
	class='arrow'
>
	<path d='M 0 2 L  0 0' />
	<path d='M 0 2 L  1 1' />
	<path d='M 0 2 L -1 1' />
</svg>

<style>
	@keyframes animate {
		50% {
			d: path('M 0 1.5 L 0 0.5');
		}
	}

	.arrow path {
		animation: animate 3s infinite;
	}
</style>

No JavaScript needed! This behavior comes free :) However, Safari doesn’t seem to support the d attribute in CSS, so that might be a deal-breaker for some.

✶ ✶ ✶