Programmatic SVGs

Saturday, March 18th 2023

There are several NPM packages available for programmatic generation of SVGs in JavaScript. Here are a few popular options:

  1. SVG.js: A lightweight library for creating and manipulating SVG elements.

  2. D3.js: A powerful data visualization library that includes tools for generating SVGs.

  3. Snap.svg: A library for creating, animating, and manipulating SVG elements.

  4. Rough.js: A library for creating hand-drawn, sketchy SVG shapes and lines.

  5. Two.js: A library for creating two-dimensional vector graphics, including SVGs.

These libraries provide a variety of tools for generating and manipulating SVGs programmatically, from simple shapes and lines to complex data visualizations. Some of them also include built-in animation tools, which can be useful for creating dynamic SVGs that respond to user interactions or changes in data.


Animate SVGs

To animate SVG XML elements and CSS attributes using JavaScript, you can use the SVG DOM (Document Object Model) and the Web Animations API. Here is an example of how to animate an SVG circle's radius and color:

<svg width="200" height="200"> <circle id="myCircle" cx="100" cy="100" r="20" fill="blue" /> </svg>
// Get a reference to the circle element const circle = document.getElementById('myCircle'); // Define the animation keyframes const keyframes = [ { r: 20, fill: 'blue' }, { r: 50, fill: 'red' }, { r: 20, fill: 'green' }, ]; // Define the animation options const options = { duration: 2000, easing: 'ease-in-out', iterations: Infinity, }; // Create a new animation const animation = circle.animate(keyframes, options); // Pause and restart the animation on click circle.addEventListener('click', () => { if (animation.playState === 'paused') { animation.play(); } else { animation.pause(); } });

In this example, we get a reference to the SVG circle element using document.getElementById, and then create a new animation using the animate method of the circle element. The animate method takes two arguments: an array of keyframes and an options object.

Each keyframe is an object that specifies the values of the SVG attributes to animate at a particular point in time. In this case, we define three keyframes that animate the circle's radius and color from blue to red to green and back to blue.

The options object specifies the duration of the animation, the easing function to use, and the number of iterations. In this case, we set the animation to run for 2 seconds, use an ease-in-out easing function, and repeat indefinitely.

Finally, we add a click event listener to pause and restart the animation when the circle is clicked.

Note that the Web Animations API is relatively new, and not all browsers support it yet. You may need to use a polyfill like web-animations-js to ensure that your animations work on all browsers.