search
HomeWeb Front-endH5 TutorialXiaoqiang'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.

Xiaoqiangs road to HTML5 mobile development (7) – Tank Battle Game 1

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 id="html-坦克大战">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>

Xiaoqiangs road to HTML5 mobile development (7) – Tank Battle Game 1

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:

Xiaoqiangs road to HTML5 mobile development (7) – Tank Battle Game 1

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()">  

小球上下左右移动

3. Let’s The tank moves


If our tank only moves in one direction, it will be very easy. Just change the drawing of a ball in the above code to drawing of a tank. Before moving the tank, the first thing we should consider is how to make the tank rotate in all directions around its center. Okay, let’s post the above picture and analyze it.

Xiaoqiangs road to HTML5 mobile development (7) – Tank Battle Game 1

I won’t go into details about the detailed calculation process. I believe everyone is good at mathematics. Calculate the coordinates and positions of each component according to the proportions of the above picture. After the tank is rotated The drawing method is as follows:

//设置颜色  
cxt.fillStyle="#BA9658";  
//上边的矩形  
cxt.fillRect(tank.x-4,tank.y+4,30,5);  
//下边的矩形  
cxt.fillRect(tank.x-4,tank.y+17+4,30,5);  
//画中间的矩形  
cxt.fillRect(tank.x+5-4,tank.y+6+4,20,10);  
//画出坦克的盖子  
cxt.fillStyle="#FEF26E";  
cxt.arc(tank.x+15-4,tank.y+11+4,5,0,360,true);  
cxt.fill();  
//画出炮筒  
cxt.strokeStyle="#FEF26E";  
cxt.lineWidth=1.5;  
cxt.beginPath();  
cxt.moveTo(tank.x+15-4,tank.y+11+4);  
if(tank.direct==1){         //只是炮筒的方向不同  
    cxt.lineTo(tank.x+30-4,tank.y+11+4);  
}else{  
    cxt.lineTo(tank.x-4,tank.y+11+4);  
}  
cxt.closePath();  
cxt.stroke();

Okay now we find that only the direction of the gun barrel is different when the tank is facing to the left and right. Similarly, only the direction of the gun barrel is different when facing up and down. At this time we can divide the four Each direction is divided into two situations, and then we deal with each small situation. At the same time, the code is encapsulated with OO ideas. The code is as follows:

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="utf-8"/>  
</head>  
<body onkeydown="getCommand();">  
<h1 id="html-坦克大战">html5-坦克大战</h1>  
<!--坦克大战的战场-->  
<canvas id="tankMap" width="400px" height="300px" style="background-color:black"></canvas>  
<script type="text/javascript">  
    //定义一个Hero类(后面还要改进)  
    //x表示坦克的横坐标  
    //y表示纵坐标  
    //direct表示方向  
    function Hero(x,y,direct){  
        this.x=x;  
        this.y=y;  
        this.speed=1;  
        this.direct=direct;  
        //上移  
        this.moveUp=function(){  
            this.y-=this.speed;  
            this.direct=0;  
        }  
        //右移  
        this.moveRight=function(){  
            this.x+=this.speed;  
            this.direct=1;  
        }  
        //下移  
        this.moveDown=function(){  
            this.y+=this.speed;  
            this.direct=2;  
        }  
        //左移  
        this.moveLeft=function(){  
            this.x-=this.speed;  
            this.direct=3;  
        }  
    }  
  
  
    //得到画布  
    var canvas1 = document.getElementById("tankMap");  
    //得到绘图上下文  
    var cxt = canvas1.getContext("2d");  
      
    //我的tank  
    //规定0向上、1向右、2向下、3向左  
    var hero = new Hero(40,40,0);  
    drawTank(hero);  
    //绘制坦克  
    function drawTank(tank){  
        //考虑方向  
        switch(tank.direct){  
            case 0:     //向上  
            case 2:     //向下  
                //设置颜色  
                cxt.fillStyle="#BA9658";  
                //左边的矩形  
                cxt.fillRect(tank.x,tank.y,5,30);  
                //右边的矩形  
                cxt.fillRect(tank.x+17,tank.y,5,30);  
                //画中间的矩形  
                cxt.fillRect(tank.x+6,tank.y+5,10,20);  
                //画出坦克的盖子  
                cxt.fillStyle="#FEF26E";  
                cxt.arc(tank.x+11,tank.y+15,5,0,360,true);  
                cxt.fill();  
                //画出炮筒  
                cxt.strokeStyle="#FEF26E";  
                cxt.lineWidth=1.5;  
                cxt.beginPath();  
                cxt.moveTo(tank.x+11,tank.y+15);  
                if(tank.direct==0){         //只是炮筒的方向不同  
                    cxt.lineTo(tank.x+11,tank.y);  
                }else{  
                    cxt.lineTo(tank.x+11,tank.y+30);  
                }  
                cxt.closePath();  
                cxt.stroke();  
                break;  
            case 1:  
            case 3:  
                //设置颜色  
                cxt.fillStyle="#BA9658";  
                //上边的矩形  
                cxt.fillRect(tank.x-4,tank.y+4,30,5);  
                //下边的矩形  
                cxt.fillRect(tank.x-4,tank.y+17+4,30,5);  
                //画中间的矩形  
                cxt.fillRect(tank.x+5-4,tank.y+6+4,20,10);  
                //画出坦克的盖子  
                cxt.fillStyle="#FEF26E";  
                cxt.arc(tank.x+15-4,tank.y+11+4,5,0,360,true);  
                cxt.fill();  
                //画出炮筒  
                cxt.strokeStyle="#FEF26E";  
                cxt.lineWidth=1.5;  
                cxt.beginPath();  
                cxt.moveTo(tank.x+15-4,tank.y+11+4);  
                if(tank.direct==1){         //只是炮筒的方向不同  
                    cxt.lineTo(tank.x+30-4,tank.y+11+4);  
                }else{  
                    cxt.lineTo(tank.x-4,tank.y+11+4);  
                }  
                cxt.closePath();  
                cxt.stroke();  
                break;    
        }  
          
    }  
      
    //接收用户按键的函数  
    function getCommand(){  
        var code = event.keyCode;  //键盘上字幕的ASCII码  
        switch(code){  
            case 87:  
                hero.moveUp();  
                break;  
            case 68:  
                hero.moveRight();  
                break;  
            case 83:  
                hero.moveDown();  
                break;  
            case 65:  
                hero.moveLeft();  
                break;  
        }  
        //把画布清理  
        cxt.clearRect(0,0,400,300);  
        //重新绘制  
        drawTank(hero);  
    }  
</script>  
</body>  
</html>


Xiaoqiangs road to HTML5 mobile development (7) – Tank Battle Game 1

##The above is Xiaoqiang’s HTML5 mobile development road (7 )——The content of Tank Battle Game 1. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)