Multiple instance canvas objects

by sungsoonz

HTML

<canvas id="canvas"></canvas>

CSS

#canvas {
  background: black;
}

JavaScript

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let moveX = 10;
let shapes = [];


class Shape {
	constructor(x, y, ctx) {
  	this.x = x;
    this.y = y;
    this.ctx = ctx;
  }
  draw() {
    this.ctx.beginPath();
    this.ctx.fillStyle = 'red';
    this.ctx.rect(this.x, this.y, 20, 20);
    this.ctx.fill();
  }
  update(moveX) {
  	this.x =+ moveX;
   	this.draw();
  }
}

for (let i = 0; i < 5; i++) {
	let yPos = 30 * i;
	shapes.push(new Shape(0, yPos, ctx));

}

const sleep = ms => new Promise(res => setTimeout(res, ms));

async function render() {
  //let rafId;
  //rafId = requestAnimationFrame(animate);
 
  let shape;
   
	for (let i = 0; i < shapes.length; i++) {
    shape = shapes[i];
	  shape.draw();
    await sleep(2000);
    	
/* 		if (shape.x > canvas.width * 0.5) {
		      cancelAnimationFrame(rafId);
		    } */
  } 
 
}

async function update() {
	ctx.clearRect(0,0,canvas.width, canvas.height);
	
  let timeId;

	timeId = setTimeout(update, 10);
  
  shapes.forEach(function(shape,index){
    moveX++;
  	shape.update(moveX);
    if (shape.x > canvas.width * 0.5) {
    	clearTimeout(timeId);
    }
    
  })
  
}

function loop() {
	render();
	update();
}

loop();