Go back
5
Now we are clearing the canvas! This starts to create a illusion of movement, but we are not quite there yet.

Clearing the canvas is similar to drawing a rectangle, except this rectangle acts as an eraser instead.

We want to clear everything, so the set the clearing rectangle to be as big as the canvas.

Once the rectangle leaves the screen it doesn't come back. You have to refresh the page to see it again.
<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)
	}
	
	let rect = { x: 0, y: 0, width: 32, height: 32, color: "blue" }
	
	function update() {
		//We tell the canvas to clear the screen so the rectangle won't duplicate itself.
		//We specifify that the clearing rectangle should cover the entire canvas.
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		
		rect.x += 40
		rect.y += 10
		
		drawRect(rect)
	}
	
	setInterval(update, 400)

</script>