How to make a smooth SVG animation with Vanilla JS

Hi guys,

I’m working on a SVG loader that needs to be pure vanilla JS. I’ve got all the elements in place using a setTimeout but would like the transitions to be smooth all the way through… Here is a pen so you can see what I mean.

At the moment it just transitions from each fill, so I’m wondering if I need like a hundred more fills and do some sort of loop to run through each fill item and hide the others as the loop increments… Or maybe there is an easier way?

Thanks in advance :slight_smile:

may want to look @ requestAnimationFrame instead of setTimeout if you want consistent and high FPS at the same time, actually been experimenting with that yesterday for one of my projects:

Cool idea, thanks … I’m just not sure if I can dynamically create each fill point, instead of hard coding every <polygon> element :confused:

you should be able to with canvas, but every point of your shaped would have be traced (dynamically) as a path, you get lot more control than svg with canvas but you loose the built in interactivity of the elements that svg offers.

I got some help on this one and here’s what we came up with, I’m pretty happy with it. I know I need to learn SVG animations properly at some point, but I think this example was much trickier than usual because I had to physically calculate the dimensions of the polygon… That’s a massive pain point, and I wonder how that can be done easily and accurately

good job, I think I misunderstood the problem as being able to create the original full path programatically…

Oh yeah… I see, in this case I was given the SVG from a Sketch file and had to work with what I had. Doing it programatically from scratch would be cool, but I definitely don’t have the skills for that. Do you know of any courses or tut’s that would help with building unique SVG images?

A while back I followed the MDN svg tutorial to build the outline of the simon game, nothing very intricate though, a few circles, concentric arcs and some horizontal lines, in principle it wasn’t too bad, however haven’t dealt much with SVG since…

You can probably avoid that: none of the browser vendors seem to have been seriously bothered about SMIL for a long time. Chrome actually deprecated the API (though it was reinstated after some people complained that there were no current solutions that allow a single self contained vector file with animations [like a GIF] outside of SVG + SMIL).


The answer is generally: you cheat. This applies to a lot of graphics stuff (all games graphics for example). You could carefully calculate the area and where all the points are, etc etc, and it would be hard. Or you could just have a rectangle, then put your shape on top (and SVG allows you to use shapes as clip paths as well). Then just animate the height of the rectangle.