Random shapes

by sosegon

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/+esm"></script>
<div id='container'>

</div>

JavaScript

import { SvJs, Gen } from "https://cdn.jsdelivr.net/npm/[email protected]/+esm"

// Parent SVG.
const svg = new SvJs().addTo(document.getElementById("container"))

// Viewport and viewBox (1:1 aspect ratio).
const svgSize = Math.min(window.innerWidth, window.innerHeight)
svg.set({ width: svgSize, height: svgSize, viewBox: "0 0 1000 1000" })

// Background.
svg.create("rect").set({
  x: 0,
  y: 0,
  width: 1000,
  height: 1000,
  fill: "#181818",
})

// Save the root svg as a downloadable file.
document.addEventListener("keydown", (event) => {
  let key = event.key.toLowerCase()
  if (key === "s") svg.save()
})

let iterations = Gen.random(500, 1000)
let shapes = ["circle", "line", "rect"]

for (let i = 0; i < iterations; i++) {
  let shape = Gen.random(shapes)
  
  // Common variables
  let x = Gen.random(200, 900)
  let y = Gen.random(300, 800)
  let fill = `hsl(${Gen.random(0, 360)} ${Gen.random(70, 80)}% ${Gen.random(60, 80)}% / ${Gen.random(50, 40)}%`
  let stroke = `hsl(${Gen.random(0, 360)} ${Gen.random(70, 80)}% ${Gen.random(60, 80)}% / ${Gen.random(50, 40)}%`
  let strokeWidth = `${Gen.random(1, 3)}`

  // Properties variables
  let props
  
  switch (shape) {
    case "circle":
      props = {
        cx: x,
        cy: y,
        r: Gen.random(1, 10),
        fill: fill,
        stroke_width: strokeWidth,
        stroke: stroke,
      }
      break;
    case 'line': 
    	props = {
      	x1: x,
        y1: y,
        x2: x + (Gen.random(-20, 20)),
        y2: y + (Gen.random(-20, 20)),
        stroke: stroke
      }
      break;
    case 'rect':
    	props = {
      	x: x,
        y: y,
        width: Gen.random(5, 25),
        height: Gen.random(5, 25),
        fill: fill,
        stroke: stroke,
        stroke_width: strokeWidth,
        transform: `rotate(${Gen.random(0, 360)} 500 500)`
      }
  }
   
  svg.create(shape).set(props)
}