Premium Features
Let's add a background image to our game using a reusable Sprite class.
Create a class that handles loading and drawing images:
class Sprite { constructor({ position, imageSrc }) { this.position = position this.image = new Image() this.image.src = imageSrc } draw() { if (!this.image) return c.drawImage(this.image, this.position.x, this.position.y) } }Wrapping constructor arguments in an object makes the code more readable — you always know what each value represents.
If your artwork uses small tiles (like 16x16 pixels), you'll need to scale it up. Use c.scale() wrapped in c.save() and c.restore():
c.save() c.scale(4, 4) background.update() c.restore()This scales only the background, leaving other game elements unaffected.
To start the player at the bottom of the map instead of the top, translate the background upward:
c.translate(0, -background.image.height + scaledCanvas.height)This formula moves the image up by its full height, then pushes it back down by the canvas height — perfectly positioning the bottom of the map on screen.
With this setup, we have a properly scaled background that we can later pan around with a camera.
Comments
Want to participate?
Create a free Chris Courses account to begin
where is the image folder for this course to download background and character sprites