Premium Features
To insert an image into canvas we need to understand how to use our context's drawImage method. We'll integrate this directly into a class, render out our background, then refactor our code so that it's as clean as possible.
Comments
Want to participate?
Create a free Chris Courses account to begin
A red square on white isn't much of a game. Let's add visual polish by loading background images and creating a reusable Sprite class for rendering any image in our game.
The Sprite Class
A sprite is simply an image with a position. Create a generic class we can reuse:
class Sprite { constructor({ position, imageSrc }) { this.position = position this.image = new Image() this.image.src = imageSrc this.loaded = false this.image.onload = () => { this.loaded = true } } draw() { if (!this.loaded) return c.drawImage(this.image, this.position.x, this.position.y) } }Loading the Background
Download the course assets and place them in an
img/folder. Then create a background sprite:const backgroundLevel1 = new Sprite({ position: { x: 0, y: 0 }, imageSrc: './img/backgroundLevel1.png' })Drawing Order Matters
In the animation loop, draw the background first so it appears behind everything else:
function animate() { window.requestAnimationFrame(animate) backgroundLevel1.draw() player.update() player.draw() }With a full-canvas background, you can remove the white fillRect that was clearing the screen.
Refactoring
Move the Sprite class to
js/classes/Sprite.jsand include it in your HTML before the Player class—Player may inherit from Sprite later when we add player images.Why This Matters
The Sprite class is a building block you'll use throughout the game—for backgrounds, doors, decorations, and eventually animated characters. One class, infinite uses.