How do you load an image with a react-p5 project?

Viewed 233

I’ve been working on a project to practise using react-p5. I’ve been trying to display an image (which is local — it’s stored in a folder called 'data' inside my project folder) on the canvas, but I’ve been running into problems where the image doesn’t seem to be loading correctly. If I try to place the image on the canvas using p5.image(), I get errors about trying to access properties of an undefined object.

I’ve tried importing the image into my sketch, then loading it using p5’s preload function. I’ve also tried using a callback with p5's loadImage() in the setup function. Neither of these approaches have worked for me and I can’t find a lot of documentation for image loading with react-p5 out there. Has anyone else had trouble loading an image when using react-p5? If so, can you point me in the right direction?

Here is the code of what I’ve tried so far:

import React, { useState } from "react";
import Sketch from "react-p5";
import background from "./data/test.png";

const Sample = (props) => {
    const [p5, setP5] = useState(null);
    let backgroundImage;

    const preload = (p5) => {
        backgroundImage = p5.loadImage(background);
    }

    const setup = (p5, parent) => {
        setP5(p5);
        p5.createCanvas(500, 500).parent(parent);
        p5.textAlign(p5.CENTER, p5.CENTER);
        
        // I've also tried loading the image this way
        // p5.loadImage("./data/test.png", img => {
        //     backgroundImage = img;
        //     p5.redraw();
        // })

        p5.noLoop();
        
    }

    const draw = (p5) => {
            p5.image(backgroundImage, 0, 0);
    }

    return <Sketch preload={preload} setup={setup} draw={draw} />
}
export default Sample;
1 Answers

You need to move your image to be somewhere in your public folder and have the relative path be relative to your index.html file.

If you move it to be in the exact same folder as your index.html file, then you can use this:

p5.loadImage("./test.png", img => {
    p5.image(img, 0, 0);
    p5.redraw();
})

https://p5js.org/reference/#/p5/loadImage

Related