Go back
6
Now the rectangle never leaves the screen! We wrote some code to make it go to the other extreme when it reaches a corner. Both horizontally and vertically.

We wrote this inside the interval function. Many further code will be written or called here, because that function will be called at each frame of our game!
<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() {
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		
		rect.x += 40
		rect.y += 10
		
		//Tell the rectangle to go back to the corner if it gets past the screen.
		
		//First horizontally
		if (rect.x > canvas.width)
			rect.x = 0
		//Then vertically
		if (rect.y > canvas.height)
			rect.y = 0
		
		drawRect(rect)
	}
	
	setInterval(update, 400)

</script>