I’m new to learning p5.js and I’m following a video right now. I’m trying to import an image but for some reason I keep getting TypeErrors: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘width’)
Here’s my code:
I’m getting the error for my draw function. For some reason my apple image isn’t loading in. It’s in my filetree and named properly.
let apple;
function preload() {
apple = loadImage("apple-o.png")
}
function setup() {
createCanvas(800, 800);
}
function draw() {
background(0);
image(apple, 100, 100)
}
When I run it with the same formatting and files in the p5 editor, everything works fine. I am using VS Code to run my code with Live Server.
Hi! This is a difference between p5.js versions. The code you have pasted here is designed for, and will work fine on, p5.js v1 versions - that’s the default in the web editor when you make a new sketch.
I suspect your local project is set up to use p5 version 2. (You can tell by looking in index.html at the libraries loaded by the <script> elements).
So you have at least two choices:
Option 1:
If you want to use p5 version 1 on your local system you should change your index.html to:
have this line <script src="https://cdn.jsdelivr.net/npm/p5@1.11.11/lib/p5.js"></script>
remove any line that loads the p5 library with a version number starting with a 2.
Option 2:
If you prefer to use p5.js version 2 locally, here’s an adjusted version of your example that will work with that version:
let apple;
async function setup(){
apple = await loadImage("apple-o.png");
createCanvas(800, 800);
}
function draw() {
background(0);
image(apple, 100, 100);
}
Happy to explain further, but hopefully that should get you past this unfortunate blocker. You should find development smooth past this point in both versions of p5.js - there are very few fundamental differences, this is one.