Go back
14
We use the canvas drawing API to draw text on screen.

We increase the score value in a separate interval function.

If you're using Dark Reader in your browser, you might want to disable it now ;)
<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
	}
	
	function updatePlayer(player) {
		player.xspeed = 0
		player.yspeed = 0
		
		let speed = 1;
		
		if (keyboard.ArrowLeft)
			player.xspeed -= speed
		if (keyboard.ArrowRight)
			player.xspeed += speed
		if (keyboard.ArrowUp)
			player.yspeed -= speed
		if (keyboard.ArrowDown)
			player.yspeed += speed
	}
	
	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 }
	
	let player = { x: 150, y: 150, width: 32, height: 32, color: "red", xspeed: 1, yspeed: 1 }
	
	let rectArray = [player, rect1, rect2, rect3]
	
	let keyboard = {}
	
	function keyDownEvent(eventInfo) {
		keyboard[eventInfo.code] = true;
	}
	
	function keyUpEvent(eventInfo) {
		keyboard[eventInfo.code] = false;
	}
	
	addEventListener("keyup", keyUpEvent);
	addEventListener("keydown", keyDownEvent);
	
	let scoreValue = 0;
	
	//we create a function for drawing text
	function drawText(text, x, y) {
		ctx.fillStyle = 'black'
		//font style attriutes: its size and font family
		ctx.font = '20px serif'
		//draw our text at these coordinates
		ctx.fillText(text, x, y);
	}
	
	//function to be called each time the score is incremented
	function incrementScore() {
		scoreValue++
	}
	
	function update() {
		ctx.clearRect(0, 0, canvas.width, canvas.height)
		
		updatePlayer(player)
		
		for (let rect of rectArray) {
			updateRect(rect)
			drawRect(rect)
		}
		
		//Draw our score using our new draw text function.
		//By "adding" something to a string, we can append text.
		drawText("Score: " + scoreValue, 10, 20);
	}
	
	setInterval(update, 4)
	//we increment our score each 500 milliseconds
	setInterval(incrementScore, 500)


</script>