In a previous article I talked about SVG’s <use>
element and how it can be used to quickly clone and transform copies of pre-existing elements. While it’s relatively straightforward to do this once or twice by hand for an SVG document, a high number of copies really require some form of automated process, most frequently in JavaScript.
The Base
While it’s possible to create absolutely everything in this illustration using pure JavaScript, it makes sense to start from a base-level markup on the page:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
<defs>
<path id="petal" d="M50 5.9c13.6 5.9 21.4 32.9 0 44.1-20.5-10.7-15-38 0-44.1z" />
</defs>
</svg>
The base SVG consists solely of a <path>
element inside a definition, meaning that nothing will appear in the document by default. Note the the viewBox
is set to 100 by 100 pixels. The rest of the drawing is generated with JavaScript.
Enhancing with JS
For this illustration I wanted 32 “petals”, meaning that each petal would appear in increments of 11.25 degrees. I created them using a for
loop:
for (var i = 0; i < 360; i += 11.25) {
var useElement = document.createElementNS("http://www.w3.org/2000/svg", "use");
useElement.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#petal");
useElement.setAttribute("fill", "hsl("+i+", 62%, 80%)");
useElement.setAttribute("transform", "rotate("+i+" 50 50)");
document.querySelector("svg").appendChild(useElement);
}
One of the benefits of using the HSL color system in CSS is that it uses circular degrees for the hue component: meaning that I could use the same number for the hue of the petal as its physical rotation. That physical rotation is around the 50 50
point of the SVG (i.e. the center of the document) where the inner tip of the single petal pattern also happens to reside.
Blending the Petals
By default the petals will appear on top of each other, in the order they are generated. I wanted them to appear both semi-transparent and blended with each other. Both of these goals can be achieved with CSS:
path {
opacity: 0.35;
mix-blend-mode: hard-light;
}
Conclusion
Variations on this technique can produce all manner of decorative illustrations very quickly, from mandalas to abstract art, some of which you can discover for yourself by playing around with the associated CodePen demo. I’ll be covering some of those applications in the future.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/YWNdNL