Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 canavs game- background not working

I am new to creating games with HTML5 canvas. I am using the angry bird style tutorial with the 'pro html5 games' book I have done everything that has been asked in the tutorial however my game background is not working....

The splash screen, the level screen and the loading screen are working fine except until I reach loading the background images for the game itself.

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

my 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.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

my 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/

Can someone please help?

like image 768
user3080734 Avatar asked Nov 01 '22 08:11

user3080734


1 Answers

there is an incomplete code.

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

see the last line?
game.an
i believe this is the problem

like image 80
vdj4y Avatar answered Nov 14 '22 18:11

vdj4y