javascript - 基于 HTML5 的游戏没有显示在浏览器上?

标签 javascript css html flappy-bird-clone

最近,我在 codepen.io 上制作了一个名为 flappy bird 的游戏,它在那里运行良好,但是当我试图在我的网站上展示它时,它没有显示任何东西。

谁能告诉我代码中缺少什么或有什么问题。 这是代码(对不起,它太长了,我知道,但我需要帮助):

<html>
<head>
<style type="text/css">
#stage {
    display:block;
    border:solid 1px #000;
    margin:auto;
}
body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;

  background:#333;
}
</style>
<script type="text/javascript">
window.requestAnimationFrame = (function(){
  return window.requestAnimationFrame || 
    window.mozRequestAnimationFrame ||                            
    window.webkitRequestAnimationFrame || 
    window.msRequestAnimationFrame || 
    function(cb){
      return setTimeout(cb, 1000/60);
    };
})()

var can = document.getElementById("stage"),
    ctx = can.getContext('2d'),
    wid = can.width,
    hei = can.height,
    player, floor, pillars, gravity, thrust, running, 
    rainbows, colider, score, gPat, pPat, trans, termVel, pillGap, 
    pillWid, pillSpace, speed, stars, high,
    sprite = document.createElement("img");
sprite.src = "http://www.cutmypic.com/uploads/title85083782.png";
//sprite.src = "http://i.stack.imgur.com/Vy3qB.gif";
sprite.onload = function(){
    sprite.style.height = 0;
    loop();
};
sprite.width = 34;
sprite.height = 21;


document.body.appendChild(sprite);

function init() {
    high = localStorage.getItem("high") || 0;

    player = {
        x: 1 / 3 * wid,
        y: 2 / 5 * hei,
        r: 13,
        v: 0
    };
    speed = 2.5;
    floor = 4 / 5 * hei;
    pillars = [];
    rainbows = [];
    stars = [];
    gravity = .30;
    thrust = gravity * -21;
    termVel = -thrust + 2;
    running = false;
    colider = false;
    score = 0;
    trans = 0;
    pillGap = 135;
    pillWid = 55;
    pillSpace = pillWid*3;
    pPat = ctx.createPattern((function(){
      var can = document.createElement("canvas"),
          ctx = can.getContext("2d");

        can.width = 60;
        can.height = 60;

        ["green", "green", "green", 
         "#3b5998", "green", "#3b5998"].forEach(function(color, i){
           ctx.fillStyle = color;

           ctx.beginPath();
           ctx.moveTo(i*10, 0);
           ctx.lineTo(i*10+10, 0);
           ctx.lineTo(0, i*10+10);
           ctx.lineTo(0, i*10);
           ctx.closePath();
           ctx.fill();

           ctx.beginPath();
           ctx.moveTo(i*10, 60);
           ctx.lineTo(i*10+10, 60);
           ctx.lineTo(60, i*10+10);
           ctx.lineTo(60, i*10);
           ctx.closePath();
           ctx.fill();
         });

      return can;
    })(), "repeat");
    gPat = ctx.createPattern((function(){
        var can = document.createElement("canvas"),
            ctx = can.getContext("2d");

        can.width = 32;
        can.height = 32;
        ctx.save();
        ctx.translate(16,16);
        ctx.rotate(Math.PI/4);
        ctx.fillStyle = "#79CDCD";
        ctx.fillRect(-64,-64,128,128);
        ctx.fillStyle = "#528B8B";
        ctx.fillRect(-8,-64,8,128);
        ctx.fillRect(14.5,-64,8,128);
        ctx.restore();

        return can;
    })(), "repeat");
}


function render() {
    trans -= speed;
    rainbows = rainbows.filter(function(r){
        r.x -= speed;
        return r.x > -speed;
    });
    if (trans % speed === 0){
        rainbows.push({x:player.x-10, y:player.y - (trans%50/25|0)*2 - 1});
    }

    stars = stars.filter(function(s){
        trans % 10 || (s.r += 1);
        s.x -= speed;
        return s.x > -speed && s.r < 10;
    });
    if(trans % 20 === 0){
      stars.push({
        x: Math.round(Math.random()*(wid-50)+100), 
        y:Math.round(Math.random()*floor), 
        r:0
      });
    }


    // backdrop
    ctx.fillStyle = "#418bbc";
    ctx.fillRect(0, 0, wid, hei);

    //stars
    ctx.fillStyle = "white";
    stars.forEach(function (s){
        ctx.fillRect(s.x, s.y - s.r-2, 2, s.r/2);
        ctx.fillRect(s.x - s.r-2, s.y, s.r/2, 2);
        ctx.fillRect(s.x, s.y+s.r + 2, 2, s.r/2);
        ctx.fillRect(s.x+s.r + 2, s.y, s.r/2, 2);

        ctx. fillRect(s.x + s.r, s.y + s.r, 2, 2);
        ctx. fillRect(s.x - s.r, s.y - s.r, 2, 2);
        ctx. fillRect(s.x + s.r, s.y - s.r, 2, 2);
        ctx. fillRect(s.x - s.r, s.y + s.r, 2, 2);

    });

    //ground

    ctx.fillStyle = "#2F4F4F";
    ctx.fillRect(0, floor, wid, hei-floor);

    ctx.save();
    ctx.translate(trans, 0);

    //pillars
    ctx.fillStyle = pPat;
    ctx.strokeStyle = "#ccc";
    ctx.lineWidth = 2;
    for (var i = 0; i < pillars.length; i++){
        var pill = pillars[i];
        ctx.fillRect(pill.x, pill.y, pill.w, pill.h);
        ctx.strokeRect(pill.x, pill.y, pill.w, pill.h);
    }

    // stripe
    ctx.fillStyle = gPat;
    ctx.fillRect(-trans, floor+2, wid, 15);
    ctx.restore();

    //rainbowwwwws
    rainbows.forEach(function(r){

        ["red","orange","blue","green","blue","indigo"].forEach(function(color, i){
            ctx.fillStyle = color;
            ctx.fillRect(r.x - speed, r.y-9 + i*3, speed+1, 3);
        });
    });

    //player
    ctx.save();
    ctx.translate(player.x, player.y);
    ctx.rotate(player.v*Math.PI/18);
    ctx.drawImage(sprite, - 17,  - 10);
    ctx.restore();

    ctx.fillStyle = "#97FFFF";
    ctx.fillRect(0, floor, wid, 2);
    ctx.fillStyle = "#2F4F4F";
    ctx.fillRect(0, floor+1, wid, 1);
    ctx.fillStyle = "#97FFFF";
    ctx.fillRect(0, floor+17, wid, 2);
    ctx.fillStyle = "#2F4F4F";
    ctx.fillRect(0, floor+17, wid, 1);


    //score
    ctx.font = "bold 30px monospace";
    var hScore = "best:" + (score > high ? score : high),
        sWid = ctx.measureText(hScore).width,
        sY = 50;

    ctx.fillStyle = "black";
    ctx.fillText(score, 12, floor + sY + 2);
    ctx.fillText(hScore, wid - sWid - 10, floor + sY + 2);  
    ctx.fillStyle = "white";
    ctx.fillText(score, 10, floor + sY);
    ctx.fillText(hScore, wid - sWid - 12, floor + sY);
}

function adjust() {
    if (trans%pillSpace === 0){
        var h;
        pillars.push({
            x: -trans + wid,
            y: 0,
            w: pillWid,
            h: (h = Math.random() * (floor - 300) + 100)
        });

        pillars.push({
            x: -trans + wid,
            y: h + pillGap,
            w: pillWid,
            h: floor - h - pillGap
        });
    }

    pillars = pillars.filter(function(pill){

        return -trans < pill.x + pill.w;
    });




    player.v += gravity;
    if (player.v > termVel){
        player.v = termVel;
    }
    player.y += player.v;

    if (player.y < player.r) {
      player.y = player.r;
      player.v = 0;
    }

    for(var i = 0; i < pillars.length; i++){
        var pill = pillars[i];
        if (pill.x + trans < player.x + player.r && 
            pill.x + pill.w + trans > player.x - player.r){           

            if (player.y - player.r > pill.y &&
                player.y - player.r < pill.y + pill.h){
                colider = true
                running = false;
                render();
                break;
            }
            if (player.y + player.r < pill.y + pill.h &&
                player.y + player.r > pill.y){
                colider = true
                running = false;
                render();
                break;
            }
            if (!pill.passed && i%2 == 1){
                score++;
                pill.passed = true;
            }
        }
    }

    if (player.y + player.r - player.v > floor) {
        player.y = floor - player.r;
        running = false;
        colider = true;
        render();
    }
}

document.onmousedown = function () {
    if (running) {
        player.v = thrust;
    } else if (!colider) {
        running = true;
    } else {
        if (score > high){
            localStorage.setItem("high", score);
        }
        init();
    }
};

</script>
</head>
<body>
<canvas id="stage" width="400" height="600"></canvas>
</body>

最佳答案

您的电话 document.getElementById('stage')之前 #stage存在于 DOM 中。

Javascript 按照加载到页面中的顺序运行。因此,您可以将 Javascript 移动到 HTML 文档的底部,或者我们 onload事件监听器。

详细来说,当页面加载时,页面顶部的内容首先被拉入并解析。当 <script>遇到标记时,浏览器会立即自动运行 Javascript——在它到达页面主体之前。您的 CodePen 可能设置为在页面完全加载后运行代码,但是当您将它全部移动到它自己的页面时,您现在正在加载之前运行它。

关于javascript - 基于 HTML5 的游戏没有显示在浏览器上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21746156/

相关文章:

javascript - 获取数据并使用ajax将其显示在文本框中

javascript - $(document).ready 仅在 IE 中触发一次,但在 Firefox 中有效

css - CSS 中列数可变的表格

jquery - JQgrid水平滚动条不显示

php - 使用 AJAX/HTML 5 上传文件

Javascript 无法在 PHP 页面中工作包括

javascript - 用 Java 解析 JavaScript

javascript - Divs show() 在不同的时间,但相关的 CSS 动画都在相同的时间轴上运行。适用于 Chrome 和 IE,不适用于 FF

html - border-radius 在嵌套 div 上的 CSS 错误外观

html - 垂直对齐多行突破