Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Setting Background Images in p5.js

Notes 2

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.

Tags: p5.js

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.