- Canvas Code Sample
- Canvas Code Sample Discussion
- Body Code
- Script Code
- Canvas Animation
- Related topics
This code sample covers the following tasks that demonstrate the basic principles of using Canvas to move an object across a detailed background:
- Setting up a game loop to process main game events
- Capturing keystrokes to determine where the ship should move next
- Saving the background where the ship will be moving to
- Moving the ship to its new position
- Restoring the old background that the ship was covering up
At the end of the code sample is discussion material that explains more about the design and structure of these tasks and how they work.
Canvas Code Sample
Canvas Code Sample Discussion
Note The code in this sample builds upon the code in the previous sample.
This section explains the design and structure of the code sample. It will tell you about the different parts and how they fit together. The Canvas sample uses a standard HTML5 header, <!doctype html>, so that browsers can distinguish it as part of the HTML5 specification.
This code is divided into two major parts:
- Body Code
- Script Code
The body code is the same as the body code in the first task of this scenario, "Drawing the background and your vehicle."
The script code contains several blocks of code fromthe first task of this scenario, "Drawing the background and your vehicle." However, the code modifies every block and adds several new ones. The script code of this sample consists of the following:
- Global variables
- canvasSpaceGame function
- stars function
- makeShip function
- doGameLoop function
- whatKey function
Global variables are called when the page loads. The canvasSpaceGame function is called from the body tag onload attribute. The rest of the functions are called from the canvasSpaceGame function.
This program uses global variable for data that will be accessed from different functions. The variables include those in the following list:
- canvas and context - you might want to make these global for most Canvas programs because you will be accessing them from many functions.
- back, oldBack – images that store the new and old background 30x30 pixel snapshots.
- ship – image that stores the pixels for the ship vehicle.
- shipX, shipY – the x and y coordinates for the ship vehicle.
- oldShipX, oldShipY – the x and y coordinates of where the ship vehicle was in its last position.
This function is based on the same function in the first task of this scenario, "Drawing the background and your vehicle." The following modifications have been made:
- A 30x30 pixel snapshot is created by using the getImageData method and saving it to the back variable. This variable is used later when the ship is moved.
- A call to setInterval, which runs the doGameLoop function every 16 milliseconds. This interval will be cancelled at the end of the game using gameLoop.
- An event handler is set up using addEventListener. This calls the whatKey function every time the keydown event takes place.
This is the same as the stars function in the first task of "Drawing the background and your vehicle." The only difference is that that a 30x30 pixel snapshot of the background is saved to the oldBack variable image for later use.
This is the same as the makeShip function in the first task of this scenario, "Drawing the background and your vehicle." The only difference is that a 30x30 pixel snapshot of the ship is saved to the ship image for later use.
This function is called every 16 milliseconds by the gameLoop timer. Game loops are very common in games because they perform basic animation tasks at regular intervals.
The game loop calls two animation tasks:
- Erasing the ship - If the ship moves and leaves a copy of the ship on the background, you must restore the old background image. This uses the putImageData method. If you do not do this, every time you move the ship, the old image of the ship remains. You must know what was under the ship before it moved and copy that image to erase the old ship image and replace it with the background image that was there before.
- Moving the ship – You must copy the ship image to the new ship position. Because this will destroy whatever image was there before, you must save the background before you destroy it.
This function is called every time a key is pressed down. It determines where the player wants the ship to move. It is important to note that the ship does not actually move in this function. The move is calculated, but the drawing of the new ship takes place in the doGameLoop function.
The whatKey function contains the following actions:
- A flag will be used to determine what happens if the ship reaches the edge of the screen.
- Before the ship can move, you must save the x and y positions of the ship and save the background that is under the ship. This is required because immediate mode does not automatically save any pixels on the screen.
- Then a switch statement processes the event and looks for the event key code. The key codes correspond to the left, right, up, and down keys on your keyboard.
- For each relevant case of the key code, the new x and y positions are calculated. If the new ship position would move the ship outside of the canvas, the new position is canceled and the flag is set.
- If the flag is set, the ship and background variables are returned to their original state.
- If the flag is not set, the getImageData method is used to save the current background snapshot.
Canvas has two ways it can create animations. The first is the most common form of animation where the screen is completely redrawn for each motion. This works better if you have a small canvas drawing surface and a fast computer. But it is not recommended for larger or more complex animation. The second way Canvas creates animations is demonstrated in the code sample included in this topic. This method is recommended for when you have a larger and more complex Canvas animation. This style of animation is more advanced. Even though it takes more code to set it up, it runs much faster than the more common style of animation. It runs faster because you only change a few individual pixels with each motion, not the entire screen of pixels. The faster style of animation shown in this sample uses the following steps. These steps are repeated in a cycle for each motion.
- Erase the ship by drawing over it with a 30x30 pixel snapshot of the old background.
- Get a new snapshot of the background that will be covered up when the ship moves.
- Draw the ship in its new position.
Because this circular loop happens every 16 milliseconds, the human eye does not see that the ship is erased, it only sees the ship as moving. This reduces the risk of screen blinking between each move, because only a small part of the screen is drawn each time.