HTML5可以让游戏背景无法正常工作

 呼呼小琰琰 发布于 2023-02-10 09:46

我是使用HTML5 canvas创建游戏的新手.我正在使用愤怒的小鸟风格教程与'pro html5游戏'一书我已经完成了教程中提到的所有内容但是我的游戏背景不起作用....

启动画面,关卡屏幕和加载屏幕工作正常,除非我加载游戏本身的背景图像.

我的HTML:



    
    
    
    






    
Score: 0
Play Game
Settings

Level Complete!/p>

Replay Current Level

Play Next Level

Return to Level Screen

我的js:

// Setup requestAnimationFrame and cancelAnimationFrame for use in the game code
 (function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame = 
         window[vendors[x]+'CancelAnimationFrame'] ||         window[vendors[x]+'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame)
    window.requestAnimationFrame = function(callback, element) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16 - (currTime - lastTime));
        var id = window.setTimeout(function() { callback(currTime + timeToCall); }, 
          timeToCall);
        lastTime = currTime + timeToCall;
        return id;
    };

if (!window.cancelAnimationFrame)
    window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
    };
}());


//The init() function is called after the page is loaded to avoid erros within in the DOM.
 $(window).load(function(){
game.init();
});

 var game={

//The following finction will allow the game to begin initilaizing the game assets and will tell the game that the start screen will be displayed first.

init: function(){
    // Initialize objects   
    levels.init();
    loader.init();

    // Hide all game layers and display the start screen
    $('.gameLayer').hide();
    $('#gameStartScreen').show();

    //Get handler for game canvas and context
    game.canvas = $('#gameCanvas')[0];
    game.context = game.canvas.getContext('2d');
},      

//Hide main menu and all other game layers and show the game level screen.
showLevelScreen:function(){
    $('.gameLayer').hide();
    $('#levelSelectScreen').show('slow');
},
// Game Mode
mode:"intro", 
// X & Y Coordinates of the slingshot
slingshotX:140,
slingshotY:280,
start:function(){
    $('.gameLayer').hide();
    // Display the game canvas and score 
    $('#gameCanvas').show();
    $('#scoreScreen').show();

    game.mode = "intro";    
    game.offsetLeft = 0;
    game.ended = false;
    game.an
},
// Maximum panning speed per frame in pixels
maxSpeed:3,
// Minimum and Maximum panning offset
minOffset:0,
maxOffset:300,
// Current panning offset
offsetLeft:0,
// The game score
score:0,

//Pan the screen to center on newCenter
panTo:function(newCenter){
    if (Math.abs(newCenter-game.offsetLeft-game.canvas.width/4)>0 
        && game.offsetLeft <= game.maxOffset && game.offsetLeft >= game.minOffset){

        var deltaX = Math.round((newCenter-game.offsetLeft-game.canvas.width/4)/2);
        if (deltaX && Math.abs(deltaX)>game.maxSpeed){
            deltaX = game.maxSpeed*Math.abs(deltaX)/(deltaX);
        }
        game.offsetLeft += deltaX; 
    } else {

        return true;
    }
    if (game.offsetLeft  game.maxOffset){
        game.offsetLeft = game.maxOffset;
        return true;
    }        
    return false;
},
handlePanning:function(){
    if(game.mode=="intro"){        
        if(game.panTo(700)){
            game.mode = "load-next-hero";
        }             
    }       

    if(game.mode=="wait-for-firing"){  
        if (mouse.dragging){
            game.panTo(mouse.x + game.offsetLeft)
        } else {
            game.panTo(game.slingshotX);
        }
    }

    if (game.mode=="load-next-hero"){
        // TODO: 
        // Check if any villains are alive, if not, end the level (success)
        // Check if there are any more heroes left to load, if not end the level (failure)
        // Load the hero and set mode to wait-for-firing
        game.mode="wait-for-firing";            
    }

    if(game.mode == "firing"){  
        game.panTo(game.slingshotX);
    }

    if (game.mode == "fired"){
        // TODO:
        // Pan to wherever the hero currently is
    }
},
showEndingScreen:function(mode){
    if (mode=="level-success"){

        if(game.currentLevel.number';
    };
    $('#levelSelectScreen').html(html); //Looks for the level select screen in the DOM.
    //Add click handlers to the level buttons
    $('#levelSelectScreen input').click(function(){
        levels.load(this.value-1);//load function i scalled by click function.
        $('#levelSelectScreen').hide(); //hide level select screen when when the clcik function is triggered.
    });
},
//Load function will load all of the images that the level requires
load:function(number){

    // declare a new current level object
    game.currentLevel = {number:number,hero:[]};
    game.score=0;
    $('#score').html('Score: '+game.score);
    var level = levels.data[number];

    //load the background, foreground and slingshot images
    game.currentLevel.backgroundImage = loader.loadImage("http://www.erin-katie.com/images/backgrounds/"+level.background+".png");
    game.currentLevel.foregroundImage = loader.loadImage("http://www.erin-katie.com/images/backgrounds/"+level.foreground+".png");
    game.slingshotImage = loader.loadImage("http://www.erin-katie.com/images/slingshot.png");
    game.slingshotFrontImage = loader.loadImage("http://www.erin-katie.com/images/slingshot-front.png");

    //Call game.start() once the assets have loaded
    if(loader.loaded){
        game.start()
    } else {
        loader.onload = game.start;
    }
}


}//Closes level variable.

var loader={

loaded:true,
loadedCount:0, // This will count the number of assets that have loaded to the game so far.
totalCount:0, // This is the total nuber of assents that the game needs to load.

init:function(){
    //Sound Support
    var mp3Support,oggSupport;
    var audio = document.createElement('audio');
    if (audio.canPlayType)  {
        mp3Support= "" !=audio.canPlayType('audio/mpeg');
        oggSupport= "" !=audio.canPlayType('audio/ogg; codecs="vorbis"');
    }   
    else {
        mp3Support=false;
        oggSupport-false;
    }

    //When support for MP3 and OGG has been checked set file extension to undefined.
    loader.soundFileExtn=oggSupport?".ogg":mp3Support?".mp3":undefined;
},
 loadImage:function(url){
    this.totalCount++;
    this.loaded = false;
    $('#loadingScreen').show();
    var image = new Image();
    image.src = url;
    image.onload = loader.itemLoaded;
    return image;
},
soundFileExtn:".ogg",
loadSound:function(url){
    this.totalCount++;
    this.loaded=false;
    $('#loadingScreen').show();
    var aduio=new Audio();
    audio.src=url+loader.soundFileExtn;
    audio.addEventListner("canplaythrough", loader.itemloaded, false);
    return audio;
},
itemLoaded:function(){
    loader.loadedCount++;
    $('#loadingMessage').html('Loaded '+loader.loadedCount+' of '+loader.totalCount);
    if (loader.loadedCount === loader.totalCount){
        // Loader has loaded completely..
        loader.loaded = true;
        // Hide the loading screen 
        $('#loadingScreen').hide('1000');
        //and call the loader.onload method if it exists
        if(loader.onload){
            loader.onload();
            loader.onload = undefined;
        }
    }
}
}//closes loader variable

我的css:

  #gameContainer {
width:640px;
height:480px;
background: url(http://www.erin-katie.com/images/splashscreen.png);
border: 1px solid black;
  }

 .gameLayer {
width:640px;
height:480px;
position:absolute;
display:none;
 }

/* ===== SPLASH SCREEN ===== */
 #gameStartScreen {
padding-top:250px;
text-align:center;
 }

 #gameStartScreen img {
margin:10px;
cursor:pointer;
 }

/* ===== LEVEL SCREEN ===== */
 #levelSelectScreen {
padding-top:215px;
padding-left:60px;  
 }

 #levelSelectScreen input {
margin:20px;
cursor:pointer;
background:url(http://www.erin-katie.com/images/icons/level.png) no-repeat;
color:#fff;
font-size: 20px;
width:64px;
height:64px;
border:0;
}
#levelSelectScreen input:hover{
background:url(http://www.erin-katie.com/images/icons/level-hover.png) no-repeat;
}
/* ===== LOADING SCREEN ===== */
#loadingScreen {
background:rgba(200,200,200,0.7);   
}

#loadingMessage {
margin-top:400px;
text-align:center;
height:48px;
color:white;
background:url(http://www.erin-katie.com/images/loader.gif) no-repeat center;
font:12px Arial;
 }
.loaderTrans    {

}
/* ===== SCORE SCREEN ===== */
#scoreScreen  {
height:60px;
font: 32px Comic Sans MS;
text-shadow: 0 0 2px #000;
color:white;
}

#scoreScreen img{
opacity:0.6;
top:10px;
position:relative;
padding-left:10px;
cursor:pointer;
}

#scoreScreen #score {
position:absolute;
top:5px;
right:20px;
}

jsFiddle:http://jsfiddle.net/Erin_Katie/DEGn7/3/

有人可以帮忙吗?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有