Table of Contents
A real front-end is definitely not a UI, and a front-end game engineer is definitely a mathematician.
Home Web Front-end H5 Tutorial Share an example code for realizing the free fall of cannonballs using HTML5

Share an example code for realizing the free fall of cannonballs using HTML5

May 06, 2017 am 11:51 AM

html5Imitation of the free fall of cannon shells

I believe everyone is familiar with the charm of html5. I hope that all browsers will support this feature soon, and Let me complain first, the WeChat broker is so weak. Simple animations, such as sliding, show(1000) and hide(1000) of jquery are not working. The core of qq browser, qq browser,,, forget it, I will calm down first. . . .

And this one I saw a few days ago! ! !

Share an example code for realizing the free fall of cannonballs using HTML5
#Why don’t you want him if you don’t support it? ? ? ? ?

Return to the theme cannon

The overall idea is to regard each fired cannonball as a
object

, and its x and y are converted into canvas 's x, y, vecior is an option to control the strength, which will be mentioned later.

var cannonBall = function (x,y,vector){
        var gravity=0,
        that={
            x: x,
            y: y,
            removeMe:false,
            move: function (){
                vector.vy += gravity;
                gravity += 0.1;
                //模拟加速度
                that.x+=vector.vx;
                that.y+=vector.vy;
                if(that.y > canvas.height -150){
                    that.removeMe=true;
                }
            },
            draw: function (){
                ctx.beginPath();
                ctx.arc(that.x,that.y,5,0,Math.PI * 2);
                ctx.fill();
                ctx.closePath();
                }
             };
Copy after login

The object of the cannonball is bound to involve vector calculations. I have encapsulated all the methods myself. There is a ready-made Vector.
js

, but I think it is too heavy ( For our back-end, every time the front-end says there is no need for templates and it is too heavy, we silently think about it, my sister, hahaha), it is very simple and can implement simple functions. It is strongly recommended to use ready-made ones for large games.

var vector2d= function (x,y){
    var vec={
        vx:x,
        vy:y,
        scale: function (scale){
            vec.vx*=scale;
            vec.vy*=scale;
        },
        add:function (vec2){
            vec.vx+=vec2.vx;
            vec.vy+=vec2.vy;
        },
        sub:function (vec2){
            vec.vx-=vec2.vx;
            vec.vy-=vec2.vy;
        },
        negate: function(){
            vec.vx=-vec.vx;
            vec.vy=-vec.vy;
        },
        length:function (){
            return Math.sqrt(vec.vx * vec.vx + vec.vy * vec.vy);
        },
        normalize:function (){
            var len=this.length();
            if(len){
                vec.vx /=len;
                vec.vy /=len;
            }
            return len;
        },
        rotate:function (angle){
            var vx = vec.vx;
            var vy = vec.vy;
            vec.vx = vx * Math.cos(angle) - vy * Math.sin(angle)
            vec.vy = vx * Math.sin(angle) + vy * Math.cos(angle);
        },
        toString:function(){
            return '(' + vec.vx.toFixed(3) + ',' + vec.vy.toFixed(3) + ')' ;
        }
    };
    return vec;
};
Copy after login

Okay, the next step is to calculate the angle and add setInterval. There is not much else to say. Here I will focus on canvas.save(); and canvas.restore( ); Here is a little explanation,
When we perform operations such as rotating, scaling, and translating the canvas, we actually want to operate on specific elements, such as

picture
, a rectangle, etc., but when When you use the canvas method to perform these operations, you are actually operating on the entire canvas, and then all elements on the canvas will be affected, so we call canvas.save() to save the current canvas ## before the operation. #State, after the operation, take out the previously saved state, so that it will not affect other elementsAll code

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta author=&#39;gongbangwei&#39;>
    <title>大炮</title>
</head>
<body>
    <p id=&#39;lidu&#39;>
        <span>选择大炮的</span>
        <input type="radio" checked=&#39;checked&#39; value=&#39;25&#39;>大
        <input type="radio"  value=&#39;20&#39;>中
        <input type="radio"  value=&#39;15&#39;>小
    </p>

    <canvas id=&#39;can&#39; width="640" height="480" style=" border:2px solid">no support html5</canvas>
    <script src=&#39;vector2d.js&#39;></script>
    <script src=&#39;jquery/jquery-1.7.2.min.js&#39;></script>
    <script>
    var gameObj=[],
    canvas=document.getElementById(&#39;can&#39;),
    ctx=canvas.getContext(&#39;2d&#39;);

    var cannonBall = function (x,y,vector){
        var gravity=0,
        that={
            x: x,
            y: y,
            removeMe:false,
            move: function (){
                vector.vy += gravity;
                gravity += 0.1;
                //模拟加速度
                that.x+=vector.vx;
                that.y+=vector.vy;
                if(that.y > canvas.height -150){
                    that.removeMe=true;
                }
            },
            draw: function (){
                ctx.beginPath();
                ctx.arc(that.x,that.y,8,0,Math.PI * 2);
                ctx.fill();
                ctx.closePath();
                }
             };

        return that;
    }
    var cannon= function (x,y,lidu){
        var mx=0,
        my=0,
        angle=0,
        that={
            x: x,
            y: y,
            lidu:lidu,
            angle:0,
            removeMe:false,
            move:function (){
                angle=Math.atan2(my-that.y,mx-that.x);
            },
            draw:function(){
                ctx.save();
                ctx.lineWidth=2;
                ctx.translate(that.x,that.y);
                //平移,将画布的坐标原点向左右方向移动x,向上下方向移动y.canvas的默认位置是在(0,0)
                ctx.rotate(angle);
                //画布旋转
                ctx.strokeRect(0,-5,50,10);
                ctx.moveTo(0,0);
                ctx.beginPath();
                ctx.arc(0,0,15,0,Math.PI * 2 );
                ctx.fill();
                ctx.closePath();
                ctx.restore();
            }
        };//end that
        canvas.onmousedown = function(){
            //在这里调用向量的那个js
            var vec = vector2d(mx-that.x,my-that.y);
            vec.normalize();
            //console.log(lidu);
            vec.scale(lidu);
            gameObj.push(cannonBall(that.x,that.y,vec));
        }
        canvas.onmousemove = function (event){
            var bb= canvas.getBoundingClientRect();
            mx=(event.clientX - bb.left);
            my=(event.clientY - bb.top);
        };
        return that;
    };
    //画蓝田和草地
    var drawSkyAndGrass = function (){
        ctx.save();
        ctx.globalAlpha= 0.4;
        var linGrad=ctx.createLinearGradient(0,0,0,canvas.height);
        linGrad.addColorStop(0,&#39;#00BFFF&#39;);
        linGrad.addColorStop(0.5,&#39;white&#39;);
        linGrad.addColorStop(0.5,&#39;#55dd00&#39;);
        linGrad.addColorStop(1,&#39;white&#39;);
        ctx.fillStyle=linGrad;
        ctx.fillRect(0,0,canvas.width, canvas.height);
        ctx.restore();

    }
    ///////main/////////////
    var lidu=$(&#39;#lidu&#39;).find("input:checked").val();
    gameObj.push(cannon(50,canvas.height-150,lidu));
    $(&#39;#lidu&#39;).click(function (event){
        var cl=event.target;
        $(this).find(&#39;input&#39;).each(function(){
            $(this).attr(&#39;checked&#39;,false)
        });
        $(cl).attr(&#39;checked&#39;,true);
        lidu=$(cl).val();
        gameObj.splice(0,gameObj.length);
        gameObj.push(cannon(50,canvas.height-150,lidu));
    })

    setInterval( function (){
        drawSkyAndGrass();
        var gameObj_fresh=[];
        for (var i = 0; i < gameObj.length; i++) {
            gameObj[i].move();
            gameObj[i].draw();
            if(gameObj[i].removeMe === false){
                gameObj_fresh.push(gameObj[i]);
            }
        }
        gameObj=gameObj_fresh;
    },50);
    </script>
</body>
</html>
Copy after login

Conclusion

A real front-end is definitely not a UI, and a front-end game engineer is definitely a mathematician.

【Related recommendations】

1.

Free h5 online video tutorial

2. HTML5 full version manual

3. php.cn original html5 video tutorial

The above is the detailed content of Share an example code for realizing the free fall of cannonballs using HTML5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SVM examples in Python SVM examples in Python Jun 11, 2023 pm 08:42 PM

Support Vector Machine (SVM) in Python is a powerful supervised learning algorithm that can be used to solve classification and regression problems. SVM performs well when dealing with high-dimensional data and non-linear problems, and is widely used in data mining, image classification, text classification, bioinformatics and other fields. In this article, we will introduce an example of using SVM for classification in Python. We will use the SVM model from the scikit-learn library

What does h5 mean? What does h5 mean? Aug 02, 2023 pm 01:52 PM

H5 refers to HTML5, the latest version of HTML. H5 is a powerful markup language that provides developers with more choices and creative space. Its emergence promotes the development of Web technology, making the interaction and effect of web pages more Excellent, as H5 technology gradually matures and becomes popular, I believe it will play an increasingly important role in the Internet world.

How to distinguish between H5, WEB front-end, big front-end, and WEB full stack? How to distinguish between H5, WEB front-end, big front-end, and WEB full stack? Aug 03, 2022 pm 04:00 PM

This article will help you quickly distinguish between H5, WEB front-end, large front-end, and WEB full stack. I hope it will be helpful to friends in need!

VUE3 Getting Started Example: Making a Simple Video Player VUE3 Getting Started Example: Making a Simple Video Player Jun 15, 2023 pm 09:42 PM

As the new generation of front-end frameworks continues to emerge, VUE3 is loved as a fast, flexible, and easy-to-use front-end framework. Next, let's learn the basics of VUE3 and make a simple video player. 1. Install VUE3 First, we need to install VUE3 locally. Open the command line tool and execute the following command: npminstallvue@next Then, create a new HTML file and introduce VUE3: &lt;!doctypehtml&gt;

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

The relationship between the number of Oracle instances and database performance The relationship between the number of Oracle instances and database performance Mar 08, 2024 am 09:27 AM

The relationship between the number of Oracle instances and database performance Oracle database is one of the well-known relational database management systems in the industry and is widely used in enterprise-level data storage and management. In Oracle database, instance is a very important concept. Instance refers to the running environment of Oracle database in memory. Each instance has an independent memory structure and background process, which is used to process user requests and manage database operations. The number of instances has an important impact on the performance and stability of Oracle database.

VAE algorithm example in Python VAE algorithm example in Python Jun 11, 2023 pm 07:58 PM

VAE is a generative model, its full name is VariationalAutoencoder, which is translated into Chinese as variational autoencoder. It is an unsupervised learning algorithm that can be used to generate new data, such as images, audio, text, etc. Compared with ordinary autoencoders, VAEs are more flexible and powerful and can generate more complex and realistic data. Python is one of the most widely used programming languages ​​and one of the main tools for deep learning. In Python, there are many excellent machine learning and deep

How to use position in h5 How to use position in h5 Dec 26, 2023 pm 01:39 PM

In H5, you can use the position attribute to control the positioning of elements through CSS: 1. Relative positioning, the syntax is "style="position: relative;"; 2. Absolute positioning, the syntax is "style="position: absolute;" "; 3. Fixed positioning, the syntax is "style="position: fixed;" and so on.

See all articles