I've been trying to create some SVG drawing animations like this: SVG animation
The problem I encounter however is how to get a proper SVG code for that. Let's say I have a png drawing and I want to convert it to SVG. When I use Inkscape I get something like this which is useless.
xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcG
Online tools like this one: SVG converter are little bit better because they output something like this:
path d="M3875 6730 c-38 -7 -902 -134 -1130 -166 -22 -3 -51 -7 -65 -9 -14
I thought that it's gonna work but I was wrong. It won't animate. How do I get a proper SVG code like in these examples?
You may first learn how svg works. Then you'll understand that convert a PNG to a SVG is not that simple.
Anyway, if you've got a real SVG (you were already mentioning something with a <path>
, you can animate it.
First, you need an SVG. Here is one with a simple path, drawing a crossed square:
<svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" style="fill: none; stroke: black">
<path d="M 10,10 l 100,0 l 0,100 l -100,0 l 0,-100 l 100,100 M 110,10 l -100,100" />
</svg>
To animate a path, we'll use a combination of two properties:
stroke-dasharray
: makes our path dashed, and defined the width of dashes and whitespacesstroke-dashoffset
: offsets our pathBasically, we'll create a dash as long as our path (or even longer), and add a high offset to make it invisible. Then we'll animate this offset to make it visible progressively:
svg {
stroke-dasharray: 1000px;
stroke-dashoffset: 1000px;
-webkit-animation: draw 5s;
animation: draw 5s;
}
@-webkit-keyframes draw {
from { stroke-dashoffset: 1000px; }
to { stroke-dashoffset: 0px; }
}
@keyframes draw {
from { stroke-dashoffset: 1000px; }
to { stroke-dashoffset: 0px; }
}
<svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" style="fill: none; stroke: black">
<path d="M 10,10 l 100,0 l 0,100 l -100,0 l 0,-100 l 100,100 l 0,-100 l -100,100" />
</svg>