Go back
8
We created a function specifically for updating rectangles, to be invoked inside our main game loop function.

This makes it easier to handle multiple rectangles, which is exactly what we are doing!

We are still manually calling the rectangle update function for each one, which isn't pratical, but that will change later.
<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)
	}
	
	//our rectangles now get their own update function, and their own individual speed values as well
	function updateRect(rect) {
		//move our rectangles by the speed values we set for each of them
		rect.x += rect.xspeed
		rect.y += rect.yspeed
		
		//we moved the wrap around mechanic here, so we don't need to repeat this code for every rect as well
		if (rect.x > canvas.width)
			rect.x = 0
		if (rect.y > canvas.height)
			rect.y = 0
		
		//this time we check for the other corners too
		if (rect.x < 0)
			rect.x = canvas.width
		if (rect.y < 0)
			rect.y = canvas.height
	}
	
	//Multiple rectangles, yay!
	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 }
	
	function update() {
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		
		//We make sure we update and draw all of them
		
		updateRect(rect1)
		updateRect(rect2)
		updateRect(rect3)
		
		drawRect(rect1)
		drawRect(rect2)
		drawRect(rect3)
	}
	
	setInterval(update, 4)


</script>