Images & Sprites
Learn how to load and display images in your p5.js games to create sprites, backgrounds, and visual elements.
Loading an Image
Use preload() to load images before your game starts:
let playerImage;
function preload() {
playerImage = loadImage('player.png');
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Display the image
image(playerImage, 150, 150);
}
Breaking it down
preload()- Special function that runs BEFOREsetup()loadImage('filename.png')- Loads an image file- Store the image in a variable so you can use it later
image(img, x, y)- Draws the image at position (x, y)
Where to Put Image Files
In p5.js Web Editor:
- Click the
>arrow next to "Sketch Files" - Click "Upload file"
- Choose your image file
- Reference it by its filename:
'player.png'
Image URL:
You can also load images from the web:
function preload() {
playerImage = loadImage('https://example.com/image.png');
}
Sizing Images
Control the size of your displayed images:
let playerImage;
function preload() {
playerImage = loadImage('player.png');
}
function draw() {
background(220);
// Image with custom width and height
image(playerImage, 100, 100, 50, 50);
}
Breaking it down
image(img, x, y, width, height)- Draws image at position with specific size- Width and height are in pixels
- Image will stretch/shrink to fit the size
Moving Images
Use variables to create moving sprites:
let playerImage;
let x = 200;
let y = 200;
function preload() {
playerImage = loadImage('player.png');
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// Move with arrow keys
if (keyIsDown(LEFT_ARROW)) {
x = x - 3;
}
if (keyIsDown(RIGHT_ARROW)) {
x = x + 3;
}
if (keyIsDown(UP_ARROW)) {
y = y - 3;
}
if (keyIsDown(DOWN_ARROW)) {
y = y + 3;
}
// Draw player image
image(playerImage, x, y, 50, 50);
}
Breaking it down
- Store position in
xandyvariables - Update position based on input
- Draw image at updated position each frame
- Creates smooth animated movement
Centered Images
By default, images draw from their top-left corner. Center them instead:
function setup() {
createCanvas(400, 400);
imageMode(CENTER);
}
function draw() {
background(220);
// Now (200, 200) is the CENTER of the image
image(playerImage, 200, 200, 50, 50);
}
Breaking it down
imageMode(CENTER)- Makes x,y refer to the image's center- Default is
imageMode(CORNER)- x,y is top-left corner - Call once in
setup()to affect all images - Makes positioning and rotation easier
Multiple Images
Load and use multiple images:
let playerImage;
let enemyImage;
let backgroundImage;
function preload() {
playerImage = loadImage('player.png');
enemyImage = loadImage('enemy.png');
backgroundImage = loadImage('background.png');
}
function draw() {
// Draw background first
image(backgroundImage, 0, 0, width, height);
// Then draw game objects
image(playerImage, 100, 200, 50, 50);
image(enemyImage, 300, 200, 50, 50);
}
Breaking it down
- Load multiple images in
preload() - Each needs its own variable
- Draw background images first (they appear behind)
- Draw player/enemies last (they appear in front)
widthandheightare canvas dimensions
Flipping Images
Flip images horizontally or vertically:
let playerImage;
let facingRight = true;
function draw() {
background(220);
push(); // Save current settings
translate(x + 25, y + 25); // Move to center of image
if (!facingRight) {
scale(-1, 1); // Flip horizontally
}
imageMode(CENTER);
image(playerImage, 0, 0, 50, 50);
pop(); // Restore settings
}
function keyPressed() {
if (keyCode === LEFT_ARROW) {
facingRight = false;
} else if (keyCode === RIGHT_ARROW) {
facingRight = true;
}
}
Breaking it down
push()andpop()- Save and restore drawing settingstranslate(x, y)- Move the drawing originscale(-1, 1)- Flip horizontally (negative x-scale)scale(1, -1)- Flip vertically (negative y-scale)
Rotating Images
Rotate images around their center:
let playerImage;
let angle = 0;
function draw() {
background(220);
angle = angle + 0.05; // Slowly increase angle
push();
translate(200, 200); // Move to center
rotate(angle); // Rotate by angle
imageMode(CENTER);
image(playerImage, 0, 0, 50, 50);
pop();
}
Breaking it down
rotate(angle)- Rotates drawing by an angle (in radians)- Rotation happens around the origin (0, 0)
- Use
translate()to move origin to where you want rotation center - Angle increases = clockwise rotation
Image Animation (Sprite Sheets)
Create animation by switching between images:
let walkImages = [];
let currentFrame = 0;
function preload() {
// Load multiple frames
for (let i = 0; i < 4; i++) {
walkImages[i] = loadImage('walk' + i + '.png');
}
}
function draw() {
background(220);
// Show current frame
image(walkImages[currentFrame], 200, 200, 50, 50);
// Change frame every 10 frames
if (frameCount % 10 === 0) {
currentFrame = (currentFrame + 1) % walkImages.length;
}
}
Breaking it down
- Store images in an array
currentFrametracks which image to showframeCount % 10 === 0- True every 10 frames% walkImages.length- Loops back to 0 after last frame
Transparency
Images with transparent backgrounds (PNG files) work automatically:
function draw() {
background(220);
// PNG with transparency shows background through it
image(playerImage, 100, 100, 50, 50);
}
Breaking it down
- Use PNG files for images with transparency
- JPG files don't support transparency
- Transparent areas show whatever is drawn behind them
Image Tinting
Change the color of an image:
function draw() {
background(220);
// Tint image red
tint(255, 0, 0);
image(playerImage, 100, 200, 50, 50);
// Tint image blue with transparency
tint(0, 0, 255, 150);
image(playerImage, 200, 200, 50, 50);
// Remove tint
noTint();
image(playerImage, 300, 200, 50, 50);
}
Breaking it down
tint(r, g, b)- Multiplies image colors by this color- Fourth parameter is transparency (0-255)
noTint()- Removes tint effect- Tint affects all images drawn after it (until
noTint())
Common Patterns
Image as Background
let bgImage;
function preload() {
bgImage = loadImage('background.png');
}
function draw() {
// Draw background filling entire canvas
image(bgImage, 0, 0, width, height);
// Draw other game elements
// ...
}
Particle Images
let particles = [];
let starImage;
function preload() {
starImage = loadImage('star.png');
}
function mousePressed() {
particles.push({
x: mouseX,
y: mouseY,
speedY: -3,
alpha: 255
});
}
function draw() {
background(220);
for (let i = particles.length - 1; i >= 0; i--) {
let p = particles[i];
tint(255, p.alpha);
image(starImage, p.x, p.y, 20, 20);
p.y = p.y + p.speedY;
p.alpha = p.alpha - 3;
if (p.alpha <= 0) {
particles.splice(i, 1);
}
}
noTint();
}
Tips & Tricks
- Use preload() - Always load images in
preload(), notsetup() - Image formats - Use PNG for transparency, JPG for photos
- File size - Smaller images load faster
- imageMode(CENTER) - Makes positioning and rotation easier
- push/pop - Always pair these when using transformations
- Free assets - Sites like itch.io have free game sprites
Common Gotchas
⚠️ Image not showing? - Check filename spelling and that file is uploaded
⚠️ Image in wrong place? - Remember: default position is top-left corner
⚠️ Rotation weird? - Use translate() before rotate()
⚠️ Load in setup? - No! Use preload() for loading images
⚠️ Slow loading? - Compress images or use smaller sizes
Related p5.js Functions
loadImage()- Load image fileimage()- Display imageimageMode()- Change how position is interpretedtint()- Color an imagenoTint()- Remove tint effectget()- Get pixel colors from an imagecopy()- Copy part of an image
Finding Free Game Art
Great websites for free game sprites:
- OpenGameArt.org - Large collection, open source
- itch.io - Many free asset packs
- Kenney.nl - High quality, free to use
- Pixabay - Free images and photos
Try It Yourself
Experiment with these ideas:
- Create a player character that walks around
- Make a game with an animated background
- Add coins or collectibles using images
- Create an enemy that chases an image sprite
- Build a simple sprite animation
Ready to learn about sound effects? Check out the Sound guide! 🔊