Go back
10
Before, we were manually calling the update function for each rectangle, but now we call that function inside a loop. The rectangles are inside an array (a list) now, and we run that loop for that list.

In other words, we are updating each of the 3 rectangles, but in a way that we don't have to repeat ourselves in the code.
<canvas id="canvas" width=300 height=300 style="border: 1px solid black; background: #EEEEEE"></canvas>

<script>

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

	function drawRect(rect) {
		ctx.fillStyle = rect.color
		ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
	}
	
	function updateRect(rect) {
		rect.x += rect.xspeed
		rect.y += rect.yspeed
		
		if (rect.x > canvas.width)
			rect.x = -rect.width
		if (rect.y > canvas.height)
			rect.y = -rect.height
			
		if (rect.x < -rect.width)
			rect.x = canvas.width
		if (rect.y < -rect.height)
			rect.y = canvas.height
	}
	
	let rect1 = { x: 0, y: 0, width: 32, height: 32, color: "blue", xspeed: 0.4, yspeed: 0.1 }
	let rect2 = { x: 0, y: 0, width: 20, height: 20, color: "green", xspeed: -0.2, yspeed: 0.05 }
	let rect3 = { x: 0, y: 0, width: 40, height: 40, color: "orange", xspeed: 0.5, yspeed: -0.1 }
	
	//we creat an array (a list of things) and store the references of our rectangles here
	let rectArray = [rect1, rect2, rect3]
	
	function update() {
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		
		//we iterate through that array, so we don't write repetitive code
		for (let rect of rectArray) {
			updateRect(rect)
			drawRect(rect)
		}
	}
	
	setInterval(update, 4)


</script>