DEV Community

Discussion on: A Generative SVG Starter Kit

Collapse
 
blindfish3 profile image
Ben Calder • Edited

Nice article. I've used dynamically generated SVG in a couple of work projects, as well as personal projects, and found it really straightforward and flexible.

One suggestion I would make: it's also possible to dynamically render SVG with a component-based framework. I've managed that with Angular (some hoops to jump through) and Svelte (straightforward). I would expect it's possible in React but haven't tried yet...

Why would you do that? It allows you to write SVG markup inside component templates and then dynamically combine these components as you wish: so you can create component-based SVGs. One major benefit of this is that you can write SVG mark-up directly rather than generating it via code. I personally don't like the approach of manually setting attributes via method calls (D3 I'm looking at you) when I can simply write them directly in my markup. An example from Svelte:

<circle  cx={x} cy={y} r={r} fill={c} />
Enter fullscreen mode Exit fullscreen mode

Here's a rather mundane chart to demonstrate the principle; and something more fun :)

One word of caution though: from what I understand browsers are not always good at optimising animation in SVG - especially Chrome-based browsers - so for anything where animation performance is critical use canvas (I highly recommend PixiJS for 2d canvas work).

edit: reference for the comment on performance: Using SVG with CSS3 and HTML5.

Collapse
 
blindfish3 profile image
Ben Calder

Since it's a slow rainy day I decided to finally try this with React; so here's a simple demo: codepen.io/blindfish3/pen/LYbaNrw

No major issues implementing this; other than having to use <g> as a wrapper on some output. From what I remember that was also required in all components on Angular - as well as some additional configuration (I'll have to look that up later).

Of the three libraries I've now tried this approach with, Svelte is definitely the easiest to use with SVGs.

Collapse
 
georgedoescode profile image
George Francis

Awesome! I love this approach, too. I have used Vue a few times to do generative art stuff. It's a lovely way of working. I really appreciate you taking the time to make a demo, too! I'll have to check out Svelte...