Cannot load image locally

This is very basic, I understand.

My code below functions in the online editor, but it does not function locally in my own computer. I’ve tried downloading the p5.js file, as well as linking to it online, but to no avail. I’ve even tried various versions of the p5.js file.

I have also run it on various browsers (Firefox, Chrome, Safari, Brave), all with the same results: I get the canvas, but no image. If I try to use a preload function, I don’t even get the canvas, just an interminable “loading…”

let img;

function setup() {
  createCanvas(423, 600);
  background(220);
  img = loadImage("images/uccello.jpg");
}

function draw() {
  image(img, 0, 0, width, height);
}

Here is a link to the functioning code in the online editor: https://editor.p5js.org/carterjohnson.sbu/sketches/M5nNcg7zo

I’ve uploaded images of my local HTML file and folder structure.

I do get an error in Firefox that reads: Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

I’d really appreciate any help. Thanks!

2 Likes

To add to @GoToLoop’s comment –

If you open your browser developer console, you’ll see that it lists a CORS error. You need to run this from a local webserver. It looks like you’re on a Mac? Which means you have Python pre-installed.

  1. Open your Terminal application
  2. Type cd (followed by a space), then drag your website folder onto the Terminal – the line look something like this: cd /Users/username/Desktop/website; hit the enter key
  3. Then type: python -m SimpleHTTPServer, then enter
  4. Open your web browser and enter http://localhost:8000 in the address bar.

The index.html file should load automatically. It should load images fine now.

* If you’ve installed Python 3, replace step 3 with python3 -m http.server

2 Likes