Setting Background Images in p5.js
Loading Background Images in p5.js
The background() function accepts an image as its first parameter, which makes it straightforward to set an image as your canvas background.
However, there's a critical timing issue to understand. The following approach will not work:
function setup() {
createCanvas(500, 500)
const bg = loadImage('./assets/background.png')
background(bg)
}
This fails because loadImage() is asynchronous. The image hasn't finished loading by the time background() is called.
The Working Pattern
The recommended approach separates image loading from rendering:
let bgImage = null
function setup() {
createCanvas(500, 500)
bgImage = loadImage('./assets/background.png')
}
function draw() {
background(bgImage)
}
By assigning the image in setup() and rendering it inside draw(), the image has time to fully load before being drawn.
Automatic Scaling Behavior
When you use background() with an image, the image scales to fill the entire canvas dimensions. In the example above, a 3073×3072 pixel image was scaled down to fit a 500×500 canvas without any cropping.
Here's another demonstration with mismatched proportions:
let bgImage = null
function setup() {
createCanvas(800, 300)
bgImage = loadImage('./assets/background.png')
}
function draw() {
background(bgImage)
}
The same image stretches to match an 800×300 canvas. This differs from the image() function, wich renders images at their original dimensions by default.
Using preload() for Resources
For maximum reliability, use preload() to handle resource loading. This function executes before setup() and is specifically designed for loading assets:
let bgImage = null
function preload() {
bgImage = loadImage('./assets/background.png')
}
function setup() {
createCanvas(500, 500)
}
function draw() {
background(bgImage)
}
This guarantees the image loads before any other code runs, eliminating potential timing issues.