jjzjj

javascript - HTML5 Canvas 游戏- 背景不工作

coder 2023-08-12 原文

我刚开始使用 HTML5 Canvas 创建游戏。我正在使用带有“专业 html5 游戏”一书的愤怒的小鸟风格教程我已经完成了教程中要求的所有内容,但是我的游戏背景无法正常工作....

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

我的 html:

<head>

    <!-- META DATA -->
    <meta charset="UTF-8">
    <meta name="author" content="Erin-Katie Strapp">
    <meta name="viewport" content="width=device-width, initial-scale = 1.0">

    <!-- CSS LINKS -->
    <link rel="stylesheet" href="css/style.css" type="text/css" />

</head>


<body>

    <div id="gameContainer"><!-- Game container holds all of tge game layers. -->
        <canvas id="gameCanvas" width="640" height="480" class="gameLayer">         
        </canvas>

        <div id="scoreScreen" class="gameLayer">
            <img id="toggleMusic" src="images/icons/sound.png">
            <img src="images/icons/prev.png">
            <span id="score">Score: 0</span>
        </div><!-- CLOSES SCORE SCREEN -->

        <div id="gameStartScreen" class="gameLayer">
            <img src="images/icons/play.png" alt="Play Game" onclick="game.showLevelScreen();"><br />
            <img src="http://www.erin-katie.com/images/icons/settings.png" alt="Settings">
        </div><!-- CLOSES GAME START SCREEN -->

        <div id="levelSelectScreen" class="gameLayer">
        </div><!-- CLOSES LEVEL SELECT SCREEN -->

        <div id="loadingScreen" class="gameLayer">
            <div id="loadingMessage"></div><!-- CLOSES LOADING MESSAGE -->
        </div><!-- CLOSES LOADING SCREEN -->

        <div id="endingScreen" class="gameLayer">
            <div>
                <p id="endingMessage">Level Complete!/p>
                <p id="playCurrentLevel"><img src="images/icons/prev.png"> Replay Current Level</p>             
                <p id="playNextLevel"><img src="images/icons/next.png"> Play Next Level </p>                
                <p id="showLevelScreen"><img src="images/icons/return.png"> Return to Level Screen</p>
            </div>
        </div><!-- CLOSES ENDING SCREEN -->

    </div><!-- CLOSES GAME CONTAINER -->

    <!-- SCRIPTS -->
    <script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script><!-- jQuery LIBRARY -->
    <script type="text/javascript" src="scripts/game.js"></script>

</body>

</html>

我的代码:

// 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.minOffset){
        game.offsetLeft = game.minOffset;
        return true;
    } else 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<levels.data.length-1){
            $('#endingMessage').html('Level Complete. Well Done!!!');
            $("#playNextLevel").show();
        } else {
            $('#endingMessage').html('All Levels Complete. Well Done!!!');
            $("#playNextLevel").hide();
        }
    } else if (mode=="level-failure"){          
        $('#endingMessage').html('Failed. Play Again?');
        $("#playNextLevel").hide();
    }       

    $('#endingscreen').show();
},

animate:function(){
    // Animate the background
   game.handlePanning();

   // Animate the characters


    //  Draw the background with parallax scrolling
        game.context.drawImage(game.currentLevel.backgroundImage,game.offsetLeft/4,0,640,480,0,0,640,480);
    game.context.drawImage(game.currentLevel.foregroundImage,game.offsetLeft,0,640,480,0,0,640,480);


    // Draw the slingshot
    game.context.drawImage(game.slingshotImage,game.slingshotX-game.offsetLeft,game.slingshotY);

    game.context.drawImage(game.slingshotFrontImage,game.slingshotX-game.offsetLeft,game.slingshotY);

    if (!game.ended){
        game.animationFrame = window.requestAnimationFrame(game.animate,game.canvas);
    }   
}
};//closes game variable

var levels={

data:[
    { //Load background images for level 1
        foreground:'planet-foreground',
        background:'space-background',
        entities:[]
    },
    { //Load background images for level 2
        foreground:'planet-foreground',
        background:'space-background',
        entities:[]
    }
],
//The follwoing init function dynamically generate each of the buttons for the levels within the game.
init: function(){
    var html="";
    for(var i=0; i<levels.data.length; i++) {
        var level=levels.data[i];
        html+= '<input type="button" value="'+(i+1)+'">';
    };
    $('#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/

有人可以帮忙吗?

最佳答案

有一个不完整的代码。

// 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
},

看到最后一行了吗?
game.an
我相信这是问题所在

关于javascript - HTML5 Canvas 游戏- 背景不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20617544/

有关javascript - HTML5 Canvas 游戏- 背景不工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  4. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  5. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  6. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  7. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  8. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  9. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  10. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

随机推荐