I Played With Canvas

Posted on Tue, 11/10/2015
2 minutes read

I started to learn canvas, and one of the first things you learn how to do is make rectangles and circles. I decided to make a random circle generator just to figure out how to do it. Turns out it's actually quite easy, well here it is.

 

See the Pen Canvas Random Circle Generator by Josh Fabean (@fabean) on CodePen.

 

The main magic happens on here:

function drawCircle() {
  i++;
  let weight = Math.pow(Math.random(), 2);
  let seed1 = Math.floor(Math.floor(weight * ((min / 2) - 0 + 1)));
  let seed2 = Math.floor(Math.random() * canvas.height);
  let seed3 = Math.floor(Math.random() * canvas.width);
  let primary = '#'+Math.floor(Math.random()*16777215).toString(16);
  let secondary = '#'+Math.floor(Math.random()*16777215).toString(16);
  let arc = {
    x: seed3 - (seed1 / 2),
    y: seed2 - (seed1 / 2),
    r: seed1,
    shadow: !(Math.random()+0.5|0),
    blur: Math.random() * (10 + 1),
    color: (!(Math.random()+0.5|0)) ? primary : secondary,
    stroke: Math.random() * (15 + 1),
    fill: !(Math.random()+0.5|0)
  };
  ctx.beginPath();
  ctx.arc(arc.x, arc.y, arc.r, Math.PI * 0, Math.PI * 2);

  if (arc.fill) {
    ctx.fillStyle = arc.color;
    ctx.fill();
  } else {
    ctx.strokeStyle = arc.color;
    ctx.lineWidth = arc.stroke;
    ctx.stroke();
  }
  if (i < 2000) {
    setTimeout(function(){
      drawCircle();
    }, 10);
  }
}

I based on the size of the canvas figure out what sizes of circles I can make, quick a random color using '#'+Math.floor(Math.random()*16777215).toString(16); which is a pretty cool way to to do it and I got it from Paul Irish. Then I based on all the values I got print the circle onto the page.

:wq