Building a Simple Game with HTML5 Canvas and JavaScript
By Prabeesh Keezhathra
- 3 minutes read - 636 wordsHTML5 introduced the <canvas> element for 2D drawing: a rectangular area on the page that JavaScript can paint into. This post walks through building a simple bird-shooting game using canvas drawing, setInterval timing, keyboard events, and basic collision detection.
Add a canvas element to the HTML document:
1<canvas id="Canvas" width="800" height="450"></canvas>
To draw inside the canvas, use JavaScript. First find the canvas element using getElementById, then initialize the context.
1 <script>
2 var canvas = document.getElementById("Canvas");
3 var context = canvas.getContext("2d")
4
5
6 </script>
To draw text on a canvas, the most important property and methods are:
font - defines the font properties for text fillText(text, x, y) - draws filled text on the canvas To set the font, size, and style of HTML5 canvas text, set the font property of the canvas context to a string containing the font style, size and family separated by spaces.
1<script>
2context.font = " 20px sans-serif";
3context.textAlign = "left";
4context.fillStyle="blue";
5context.textBaseline = "top"
6context.fillText("Press Enter Key to start the game", 240,10);
7</script>
To draw an image on a canvas use the following method drawImage(image, X, Y, Width, Height)
1<script>
2var bird = new Image();
3bird.src = 'bird.png';
4context.drawImage(bird, posX, posY, Width, Height);
5</script>
To rotate the HTML5 Canvas, use the rotate() transform method. The rotate transformation requires an angle in radians. context.rotate(angle);
1<script>
2context.rotate(Math.PI/60);
3context.drawImage(gun, 0, 0, 150, 50);
4</script>
To get the event occurring in the document, use EventListener.
1document.addEventListener('keydown', function);
The functions used for game development are
The WhichKey() function reads the keyboard input. The UP/DOWN arrow keys control gun movements. The Enter key starts the game. The space key fires.
1function WhichKey(event) {
2 if (event.keyCode==38) //UP arrow
3 gunUpMove();
4 if (event.keyCode==40) //Down arrow
5 gunDownMove();
6 if (event.keyCode==32) // Space Key
7 firing();
8 if (event.keyCode==13) //Enter Key
9}
The counter() function sets up a countdown timer. Using setInterval(function, timeInMs), the counter is called every 1000 ms (1 second).
1var count = 60;
2clear=setInterval(counter, 1000);
3function counter() {
4 count-= 1;
5 if (count <= 0) {
6
7 clearInterval(clear);
8
9 }
10
11//code for show the counter
12}
The birdAppearing() is used for appearing bird on the canvas at random points and disappear after a particular interval.
1function birdAppearing() {
2 if (start==1) {
3 var posx = Math.floor((Math.random()*635)+85);
4 var posy = Math.floor((Math.random()*305)+85);
5 context2.drawImage(bird, posx, posy, 40, 40);
6 posX = posx;
7 posY = posy;
8 setTimeout(function() {context2.clearRect(0, 0, 800, 450);
9 birdAppearing();
10 },2000);
11 }
12}
The firing() is used for creating red dotted lines in canvas. If the dotted line coordinates exceed the canvas coordinates then it restores to the initial position. The end point coordinate of the dotted line always compares with the coordinates of the center point of the bird image. If the difference between these points less than the radius of the circle centered at bird image then dotted lines restore the initial position and also the bird will die and get a point.
1function firing() {
2 while(1) {
3 context.strokeStyle = "red";
4 context.lineWidth = 2;
5 context.beginPath();
6 context.moveTo(fireStart+= 8,14);
7 context.lineTo(fireEnd+= 8,14);
8 context.stroke();
9 if ((fireEnd*Math.cos(angle*Math.PI/60)) >800 || (fireEnd*Math.sin(angle*Math.PI/60)) >450){
10
11 setTimeout(function() {
12 context.clearRect(85, 10, fireEnd, 6);
13 fireStart = 85;
14 fireEnd = 87;
15 },16);
16 return;
17 }
18 if (Math.abs(posX+20-(fireStart*Math.cos(angle*Math.PI/60))) < 20 && (Math.abs( posY+20-(fireEnd*Math.sin(angle*Math.PI/60))) < 20)) {
19 setTimeout(function() {
20 context.clearRect(85, 10, fireEnd, 6);
21 fireStart = 85;
22 fireEnd = 87;
23 },16);
24 context2.clearRect(0, 0, 800, 450);
25 context2.drawImage(deadBird, posX, posY, 60, 60);
26
27 score += 1;
28 context0.font = " 20px sans-serif";
29 context0.textAlign = "left";
30 context0.fillStyle="black";
31 context0.textBaseline = "top";
32 context0.clearRect(200, 0, 800, 500);
33 context0.fillText('Score :'+ score, 700, 10);
34 return;
35 }
36 }
The source code is available here.