Home > Article > Web Front-end > Xiaoqiang’s road to HTML5 mobile development (7) – Tank Battle Game 1
In the previous article, we introduced the basic knowledge about Canvas and used Canvas to draw various graphics and pictures. Based on the previous article, we will make a tank battle game based on HTML5. Let’s get started.
1. Use Canvas to draw our tank
The tank structure we designed is as shown in the picture below. If some friends have better designs, I hope to share and communicate with them.
As shown in the picture above, our tank is basically composed of three rectangles, a circle and a line segment. The size of each component is marked in px , let’s use the knowledge mentioned in the previous article to draw our tank. Note: When we draw the tank, we should choose a reference point. Here we choose the upper left corner of the tank, as shown in the picture.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <h1>html5-坦克大战</h1> <!--坦克大战的战场--> <canvas id="tankMap" width="400px" height="300px" style="background-color:black"></canvas> <script type="text/javascript"> //得到画布 var canvas1 = document.getElementById("tankMap"); //定义一个位置变量 var heroX = 80; var heroY = 80; //得到绘图上下文 var cxt = canvas1.getContext("2d"); //设置颜色 cxt.fillStyle="#BA9658"; //左边的矩形 cxt.fillRect(heroX,heroY,5,30); //右边的矩形 cxt.fillRect(heroX+17,heroY,5,30); //画中间的矩形 cxt.fillRect(heroX+6,heroY+5,10,20); //画出坦克的盖子 cxt.fillStyle="#FEF26E"; cxt.arc(heroX+11,heroY+15,5,0,360,true); cxt.fill(); //画出炮筒 cxt.strokeStyle="#FEF26E"; cxt.lineWidth=1.5; cxt.beginPath(); cxt.moveTo(heroX+11,heroY+15); cxt.lineTo(heroX+11,heroY); cxt.closePath(); cxt.stroke(); </script> </body> </html>
2. How to make the tank move?
Before studying how to make the tank move, let’s first study how to make a small ball move through keyboard operation.
First we add a listening function to the
tag<body onkeydown="test()">
Listening function
//现在按键盘上ASDW移动小球 //说明:当我们按下一个键,实际上触发了一个onkeydown事件 function test(){ var code = event.keyCode; //键盘上字幕的ASCII码 switch(code){ case 87: ballY--; break; case 68: ballX++; break; case 83: ballY++; break; case 65: ballX--; break; } //重新绘制 drawBall(); }
We can define two global variables externally to represent the x-axis and y respectively. The coordinates of the axis, and then change the position of the ball by changing the values of ballX and ballY. We use the WDSA key of the keyboard to control it. The effect is very strange, as shown below:
We did not erase the ball at the previous position when drawing. We should erase it before each redrawing. Post all the codes below:
<body onkeydown="test()">小球上下左右移动