| |

Javascript, canvas and animation not running in all browsers

I’m the world’s biggest hypocrite when it comes to documentation. In every staff meeting, I emphasize documenting whatever code you have written that week, but I always put off doing it myself.  My excuse is always that it isn’t final and when I get the complete project done I will put it in the wiki.

I’ve come to the conclusion that no complex software is ever done. You just quit working on it and go to something else.

If you have run into the awful problem of having your animation run on some browsers and not others, or even run sometimes and sometimes not in the same browser, you may have a timing problem. In brief, you are trying to draw the image before it is loaded.

Here is what I did today and how I fixed that problem…

In this part of the game (Forgotten Trail) , the player has answered a question that asks for the average number of miles the uncle walked each day when he attempted this journey.  If the player gives the correct answer, say, 22 miles, a screen pops up and the mother asks, “Do you really think you can walk 22 miles a day?” If the player says, “No,” then he or she is sent to workout. Each correct answer runs your character 5 miles. After 20 miles, you can go back to the game.

Sam is running

So …. we need animation and sound that occurs when a correct answer is submitted. I had finished the code to randomly generate division problems, so today I was working on the function after the player is correct.

The HTML elements are pretty simple – a div that contains everything, two layers of canvas, a button and two audio elements.

HTML

<div id="container">
<canvas id="layer1" style="z-index: 1; position:absolute; left:0px; top:5px;"
 height="400px" width="900"> This text is displayed if your browser does not support HTML5 Canvas. 
</canvas> 
<canvas id="layer2" style="z-index: 1; position:absolute;left:0px;top:5px;" 
height="400px" width="900"> This text is displayed if your browser does not support HTML5 Canvas.
 </canvas>
 <button id="workout" name="workout" >CLICK TO WORK OUT</button> </div> 
<audio autoplay id="audio1"><source type="audio/ogg"></audio> 
<audio autoplay id="audio2"><source type="audio/mpeg"></audio>
</div>

Because the character is only moving horizontally – he is running on a field – there is no dy and no y variable.

JAVASCRIPT


<script type="text/javascript">
    // INITIALIZE VARIABLES FOR CANVAS CONTEXT, LAYERS, HEIGHT & WEIGHT ;
    // ALSO INITIALIZE THE PLAYER ELEMENTS WE'LL DRAW;
    // BECAUSE THE PLAYER IS RUNNING, I LEFT OUT THE MIDDLE TWO FRAMES FOR THE SPRITE ;
    var layer1;
    var layer2;
    var ctx1;
    var ctx2;
    var animationFrames =[
        "game_art/sam1.png", "game_art/sam4.png"];
    var frameIndex = 0 ;
    var dx = 0 ;
    var x = 150;
    var width = 900;
    var height = 600;

    var player = new Image();
    var bkgd = new Image() ;


// DRAWS THE TWO LAYERS ;

    function drawAll() {
        draw1();
        draw2();

    }

// DRAWS THE BACKGROUND LAYER ;

    function draw1() {
        ctx1.clearRect(0, 0, width, height);
        ctx1.drawImage(bkgd, 0, 0);
    }

// SOLVES THE PROBLEM THAT WAS DRIVING ME CRAZY BY ADDING AN EVENT LISTENER ;
// NOW, WE DON'T TRY TO DRAW THE IMAGE UNTIL IT IS LOADED ;
    function draw2() {
        dx = 10;
        x = x + dx;
        ctx2.clearRect(0, 0, width, height);
         player.src = animationFrames[1];
        ctx2.drawImage(player, x,320);
        frameIndex++ ;
        if (frameIndex == 1) {
            ctx2.clearRect(0, 0, width, height);
            player.src = animationFrames[0];
     // THE STATEMENT BELOW RESTORED MY SANITY ;
            player.addEventListener('load', drawImage);
        }
        else  {
            ctx2.clearRect(0, 0, width, height);
            player.src = animationFrames[1];
            player.addEventListener('load', drawImage);
            frameIndex = 0 ;
        }
    }

// ONCE THE IMAGE IS LOADED, THIS FUNCTION IS CALLED ;

    function drawImage(){
        ctx2.drawImage(player, x,320);
    }
 
// WE ONLY SET THE BACKGROUND SOURCE ONCE, WHEN THE WINDOW LOADS ;
// 
   window.onload =function(){
        bkgd.src ="game_art/fields.png";
        layer1 = document.getElementById("layer1");
        ctx1 = layer1.getContext("2d");
        layer2 = document.getElementById("layer2");
        ctx2 = layer2.getContext("2d");

// EVERY 100 MILLISECONDS WE DRAW 
        var interval = setInterval(function(){
            draw1();
        }, 100);
        document.getElementById("workout").onclick = function drawnow(){
            var startTime = new Date().getTime();
            var interval = setInterval(function(){
                if(new Date().getTime() - startTime > 9000){
                    document.getElementById("audio1").src = "";
                    document.getElementById("audio2").src = "";
                    clearInterval(interval);
//   LATER I WILL ADD HERE TO STOP AFTER RUNNING 1/4 THE DISTANCE;
                }
                drawAll();
            }, 100);

// THIS MAKES THE SOUND OF RUNNING WHILE THEY ARE RUNNING ;
            document.getElementById("audio1").src = "sounds/footsteps_run.ogg";
            document.getElementById("audio2").src = "sounds/footsteps_run.mp3";
        }

    }
</script>

 

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *