<div id="container">
<canvas id="mycanvas" width="640" height="480">
</canvas>
  
<div>
  <div>Add a new Particle</div>
  <button class="controller" onclick="addNewRandomParticle()"> ADD </div>
</div>
</div>
#container {
  display: flex;
  flex-direction: row;
}

button.controller {
  padding: 5px 15px;
  min-width: 122px;
  border-radius: 5px;
  border: none;
  font-family: 'helvetica';
  background: #7371e0;
  color: white
}
let sceneGraph = [];
class Particle{
  constructor(cx, cy, r, fill){
    this.cx = cx;
    this.cy = cy;
    this.r = r;
    this.fill = fill;
  }
  
  update(ctx){
      ctx.fillStyle = this.fill;
      ctx.beginPath();
      ctx.arc(this.cx, this.cy, this.r, 0, 2*Math.PI);
      ctx.closePath();
      ctx.fill();
  }
}

function redrawSurface(){
  let canvas = document.getElementById("mycanvas");
  let ctx = canvas.getContext("2d");
  ctx.clearRect(0,0, canvas.width, canvas.height);
  for(obj of sceneGraph){
    obj.update(ctx)
  }
}

function addNewRandomParticle(){
  let x = Math.floor(Math.random()*640);
  let y = Math.floor(Math.random()*480);
  let r = Math.ceil(Math.random()*9+1);
  let color = `rgb(${
Math.ceil(Math.random(0)*255)}, ${
Math.ceil(Math.random(0)*255)}, ${
Math.ceil(Math.random(0)*255)})`
  let part = new Particle(x, y, r, color);
  sceneGraph.push(part);
  console.log(part)
  redrawSurface();
}



window.onload = function(){
  let canvas = document.getElementById("mycanvas");
  let ctx = canvas.getContext("2d");
  
  sceneGraph.push(new Particle(30, 30, 10, "red"))
  redrawSurface()
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.