javascriptp5.js

Setting a photo as background in p5.js


I am trying to upload a photo as a background in p5.js. Unfortunately I become 2 error messages in the console.

    p5.js:74522 Fetch API cannot load file:///C:/Users/User/Desktop/project/sample.png. URL scheme must be "http" or "https" for CORS request.
_main.default.loadImage @ p5.js:74522
setup @ sketch.js:15
_setup @ p5.js:58811
_start @ p5.js:58739
p5 @ p5.js:59080
_globalInit @ p5.js:58340
load (async)
25.../core/main @ p5.js:58353
o @ p5.js:34
(anonymous) @ p5.js:38
16../color/color_conversion @ p5.js:52829
o @ p5.js:34
r @ p5.js:51
(anonymous) @ p5.js:55
(anonymous) @ p5.js:18
(anonymous) @ p5.js:20

p5.js:74522 Uncaught (in promise) TypeError: Failed to fetch
    at p5._main.default.loadImage (p5.js:74522)
    at setup (sketch.js:15)
    at p5._setup (p5.js:58811)
    at p5._start (p5.js:58739)
    at new p5 (p5.js:59080)
    at _globalInit (p5.js:58340)

That's my code:

var back;

function setup() {
  createCanvas(800, 600);
  back = loadImage("sample.png");
}

function draw() {
    background(back);
}

Where is my mistake and what can I do for the photo to be shown? Thank you in advance! Looking forward to hearing from you.


Solution

  • I solved the problem with loading the background image in the preload() function:

    function preload() {
      back = loadImage("sample.png");
    }
    
    function setup() {
      createCanvas(800, 600);
    }
    
    function draw() {
        background(back);
    }