Go back
2
We create a function to make drawing a rectangle more pratical.

Now instead of having to specify the dimensions and the color in separate instructions, now we can do these things in one go.

Avoid repeating yourself with the usage of functions is a fundamental principle in programming.
<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')
	
	//We create a function to automate our work a little
	function drawRect(x, y, width, height, color) {
		ctx.fillStyle = color
		ctx.fillRect(x, y, width, height)
	}
	
	//Now we can call those lines of code above without repeating them:
	drawRect(100, 50, 80, 40, "red")
	drawRect(100, 150, 80, 40, "blue")


</script>