Home  >  Article  >  Web Front-end  >  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

零下一度
零下一度Original
2017-05-06 11:51:251892browse

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();
                }
             };

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;
};

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>
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:
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