Moving Background
Categories: LessonsIntro to JavaScript, creating a moving background
Hack/More information
Using what was taught in the lesson you will create a moving background.
Requirements:
- Being able to size the Canvas correctly
- Create a canvas element with an id
- Use JavaScript to get the canvas and 2D context.
- Succsessfully creating a class for the game object
- Class must contain properties for image, width, height, speed, and speedRatio
- Creating a background class
- Background class must extend to game object
- Add an update() that moves the background around so it never ends
- Creating a Game loop
- Must have an Animate() function that clears the canvas, redraws the background, and draws the sprite in the center
- Working final output
Troubleshooting
Canvas isn’t showing anything
- Make sure you are using the correct id in document.getElementById(“world”).
- Verify your canvas has a width and height set in JavaScript:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//Should look like this
Images don’t appear
- Make sure your images exist in the same folder or the correct path is used.
- Check that you load the image before drawing it, don’t try to draw the image before it has loaded.
Background isn’t moving
- Check your update() function in the Background class
- Make sure speed is not zero.
- Make sure animate() calls backgroundObj.update() every frame
this.x = (this.x - this.speed) % this.width;
//What the update() function in the background class should look like
Background disappears or gaps appear
- Ensure your draw(ctx) method draws two copies of the background:
- This prevents gaps when one image scrolls off the screen.
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
ctx.drawImage(this.image, this.x + this.width, this.y, this.width, this.height);
//What the draw() function in the background class should look like