Home  >  Article  >  Web Front-end  >  Share the sample code for creating html5 Star Trek yourself

Share the sample code for creating html5 Star Trek yourself

黄舟
黄舟Original
2017-04-01 11:26:101753browse

Studyhtml5canvasOn the third day, I feel that it is still good It’s not fun and I forget about it in a blink of an eye, so I’m going to make a little game to play when I have free time! The game should pay attention to performance, and there are some logics that need to be considered. I think it also needs user modifiability, that is, user configuration. Let’s start our simple but interesting journey -

If you want to see the effect first, jump and try it out first! Step, of course you need a canvas

1 <canvas id="canvas" width="300" height="400">你的浏览器不支持Canvas</canvas>

The overall structure of JavaScript

is as follows:

var定义一些变量
planeMoveTimer飞机移动监听/计时器
attackEnemyTimer发射炮弹计时器
onkeydown监听
onkeyup监听
drawPlane画飞机
drawEnemy画敌人
First predefine some variables
var _keyA = _keyD = _keyW = _keyS = 0,  // 存储按键状态

    step = 8,                          // 飞机移动速率
    w = 34, h = 44,                  // 飞机实际大小
    planeX = 133, planeY = 356,      // 飞机目前位置
    planeSrc = "feiji.png",          // 飞机素材位置
    imgW = 177, imgH = 220,          // 飞机源图尺寸

    cw = 300, ch = 400,  // 画布大小
    canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

This game only uses An external resource is the

picture

. To obtain the address, please visit the project GitHub location link given at the bottom of this article. Jump

Look at the two methods of drawing first

function drawPlane(x, y) {
    var img = new Image();
    img.src = planeSrc;  // 飞机源图地址
    img.onload = function() {
        ctx.drawImage(img, 0, 0, imgW, imgH, planeX, planeY, w, h);
    }
}
function drawEnemy(){
    for(var a=0;a<cw;a+=10) {
        for(var b=0;b<ch-300;b+=10) {
            ctx.beginPath();
            ctx.fillStyle = "orange";
            ctx.strokeStyle = "black";
            ctx.strokeRect(a, b, 10 ,10);
            ctx.fillRect(a, b, 10, 10);
            ctx.closePath();
        }
    }
}
##. # The picture of the airplane must be drawn in the onload() method. The current enemy is still a bunch of orange bricks that cannot move. Draw them at the top of the canvas by traversing

Then. , look at the two keyboard

events

:

window.document.onkeydown = function(evt){
    evt = (evt) ? evt : window.event;
    switch(evt.keyCode) {
        case 65:  // A
            _keyA = 1;
            break;
        case 68:  // D
            _keyD = 1;
            break;
        case 87:  // W
            _keyW = 1;
            break;
        case 83:  // S
            _keyS = 1;
            break;
    }
}
window.document.onkeyup = function(evt){
    evt = (evt) ? evt : window.event;
    switch(evt.keyCode) {
        case 65:  // A
            _keyA = 0;
            break;
        case 68:  // D
            _keyD = 0;
            break;
        case 87:  // W
            _keyW = 0;
            break;
        case 83:  // S
            _keyS = 0;
            break;
    }
}

As for why the variables _keyA, _keyD, _keyW, _keyS should be set in the two events instead of directly triggering the drawing event, the reason is—— When two keys are long pressed at the same time, the event cannot be triggered at the same time. The one who presses first will only trigger it once. Only the one who presses later can trigger the event all the time while the key is pressed. To put it simply, if I want to move to the upper left corner, at the same time Press A and W. Assume that A is a little slower than W, even if it is very small, then the movement path of the aircraft is to move up one step first and then move all the way to the left. This is obviously not what I want. I use 4 variables to store it. The status of the key. When the key is pressed, set its status to 1. When the key is pressed, set its status to 0. Then we use a timer to continuously read the status of these keys and update them in time The status of the aircraft.

The aircraft movement timer is as follows:

var planeMoveTimer = window.setInterval(function(){
    if(_keyA||_keyD||_keyW||_keyS){
        ctx.clearRect(planeX, planeY, w, h);
        _keyA && (planeX-=step);
        _keyD && (planeX+=step);
        _keyW && (planeY-=step);
        _keyS && (planeY+=step);
        planeX>=0 || (planeX=0);
        planeX<=(cw-w) || (planeX=cw-w);
        planeY>=0 || (planeY=0);
        planeY<=(ch-h) || (planeY=ch-h);
        drawPlane(planeX, planeY);
    }
}, 10);
ctx.clearRect() is used to clear the original position of the aircraft in preparation for drawing the next state of the aircraft, but there is a very The big problem is that it directly clears the entire block. If the game has backgrounds and overlaps, doesn't it mean that these things that are not airplanes are also cleared? Forgive me for being ignorant, I will not consider this issue for now.

By judging the button status, the step distance of each movement is the preset step, and the boundary processing is done

Then the attack timer:

var attackEnemyTimer = window.setInterval(function(){
    var cannonX = planeX+Math.floor(w/2);  // 炮口X轴位置
    var cannonY = planeY;  // 炮口Y轴位置
    var tmpTimer = window.setInterval(function(){  // 每颗炮弹的移动计时器
        ctx.clearRect(cannonX-1, cannonY-3, 2, 3);
        cannonY -= 3;  // 炮弹步距
        if(cannonY<0){
            // 炮弹的贯透效果
            ctx.beginPath();
            ctx.moveTo(cannonX, 100);  // 100为enemy的最低位置
            ctx.strokeStyle = "white";
            ctx.lineWidth = "4";  // 模拟不规则毁坏,暂时尚未没实现
            ctx.lineTo(cannonX, 0);
            ctx.stroke();
            ctx.closePath();
            window.clearInterval(tmpTimer);  // 清除该炮弹的计时器
        }
        ctx.clearRect(cannonX-1, cannonY-3, 2, 3);
        ctx.beginPath();
        ctx.fillStyle="red";
        ctx.fillRect(cannonX-1, cannonY-3, 2, 3);  // 炮弹大小:2X3
        ctx.closePath();
    }, 0);
}, 500);

Launch one every 0.5s. For the cannonballs, each cannonball is set up with a separate timer for easy control. I also use the method of wiping first and then painting for the movement of the cannonballs. Since the movement of the cannonballs also has steps, the so-called penetration effect of the cannonballs is to directly draw a line with the same color as the background color. Just a straight line. Try modifying the cannonball stride to adjust the speed of the cannonball, as well as the size of the cannonball.

This is the last step. There is nothing left to do. We need to draw the enemies and planes from the beginning!

1 drawPlane();
2 drawEnemy();

Done! I still want to continue to optimize and increase the playability, but I really don’t have time to do it. There are many other things to learn, so this game will be like this for now! Is not it simple! Haha, it’s embarrassing, the title is too tempting, I can’t help it!

The above is the detailed content of Share the sample code for creating html5 Star Trek yourself. 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