DEV Community

Cover image for SVG Circle Pattern Generator
Mads Stoumann
Mads Stoumann

Posted on

12 1

SVG Circle Pattern Generator

The other day – trying to empty my head and relax a bit – I stared at the colorful rug next to my chair:

Hay Rug

And suddenly, instead of emptying my head, I started to wonder about how I could re-create this in svg — that is: repeating circles with random colors!


When working with random patterns, the first thing you need is a random function:

function R(max, min = 0) {
  return Math.floor(Math.random() * (max - min) + min);
};
Enter fullscreen mode Exit fullscreen mode

If you call it like R(360), it will return a random number between 0 and 360. If you add a second parameter, like R(360, 200), it will limit the random number to a number between 200 and 360.

The circles are created within a dual loop – one for the y-axis, and one for the x-axis (excerpt) :

<circle
  cx="${cx}" cy="${cy}" r="${r}" 
  fill="hsl(${R(A.elements.he.valueAsNumber,
 A.elements.hs.valueAsNumber)},
 ${R(A.elements.se.valueAsNumber,
 A.elements.ss.valueAsNumber)}%,
 ${R(A.elements.le.valueAsNumber,
 A.elements.ls.valueAsNumber)}%)"
/>
Enter fullscreen mode Exit fullscreen mode

Most of the code deals with the random colors.

hsl() is perfect for this, since it's three ranges of numbers, that can be randomized:

  • hue (0-360)
  • saturation (0-100)
  • lightness (0-100)

A is the main form for editing the variables:

Form

– and as mentioned above, you can limit the randomness, in this case the hue (min and max):

circles

If you set the radius to a larger value than the size, you end up with something similar to my rug:

Pattern

Here's a Codepen with the final result. Open it in fullscreen, click on the rotating cog-wheel to open the editor, and have fun!

If you want, you can save the pattern you create as either png, jpg or webp — just select a type, and click on Save to Image.

Thanks for reading!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay