The Player Ship State Changes

We simply need to switch between the static and thrust states to simulate the animation. Let’s take a look at the full HTML file to do this. In Example 8-4, we will start to place canvasApp class-level variables in a new section just above the drawScreen() function. This will be the location going forward for all variables needing a global scope inside the canvasApp() object.

Example 8-4. The player ship state changes for thrust animation

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH8EX4: Ship Animation Loop</title>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {

   canvasApp();
}

function canvasApp(){

   var theCanvas = document.getElementById("canvas");
   if (!theCanvas || !theCanvas.getContext) {
          return;
   }

   var context = theCanvas.getContext("2d");

   if (!context) {
          return;
   }

   //canvasApp level variables
   var shipState = 0; //0 = static, 1 = thrust

   function drawScreen() {
      //update the shipState
      shipState++;
      if (shipState >1) {
         shipState=0;
    }

    // draw background and text
    context.fillStyle = '#000000';
    context.fillRect(0, 0, 200, 200);
    context.fillStyle = '#ffffff';
    context.font = '20px sans-serif';
    context.textBaseline = 'top';
    context.fillText  ("Player Ship - animate", 0, 180);

    //drawShip
    context.strokeStyle = '#ffffff';
    context.beginPath();
    context.moveTo(10,0);
    context.lineTo(19,19);
    context.lineTo(10,9);
    context.moveTo(9,9);
    context.lineTo(0,19);
    context.lineTo ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.