snowflakes

by aio350

HTML

<canvas width="300" height="300" style="border: 1px dotted #222"></canvas>

CSS

body {
  margin: 0;
  height: 100vh;
  background: radial-gradient(circle, skyblue, steelblue);
  display: flex;
  justify-content: center;
  align-items: center;
}

JavaScript

const canvas = document.querySelector('canvas')
const $ = canvas.getContext('2d')

const deg = Math.PI / 180

function snowflake($, n, x, y, r) {
  $.save()
  $.translate(x, y)
  $.moveTo(0, 0)
  angle(n)
  $.rotate(-120 * deg)
  angle(n)
  $.rotate(-120 * deg)
  angle(n)
  $.closePath()
  $.restore()

  function angle(n) {
    $.save()
    if (n == 0)
      $.lineTo(r, 0)
    else {
      $.scale(1 / 3, 1 / 3)
      angle(n - 1)
      $.rotate(60 * deg)
      angle(n - 1)
      $.rotate(-120 * deg)
      angle(n - 1)
      $.rotate(60 * deg)
      angle(n - 1)
    }
    $.restore()
    $.translate(r, 0)
  }
}

snowflake($, 1, 20, 100, 105)
snowflake($, 2, 180, 100, 105)
snowflake($, 3, 10, 255, 125)
snowflake($, 4, 170, 255, 125)
$.fillStyle = '#ddd'
$.fill()
$.strokeStyle = '#222'
$.stroke()