p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

How not to re-render the canvas once state changes?

Open nijatmursali opened this issue 1 year ago • 2 comments

Topic

I have couple of states where I change on different parts of the project:

which are:

    const [sketchDimensions, setSketchDimensions] = useState(SHOE_DIMENSIONS);
    const [selectedSegment, setSelectedSegment] = useState(null);
    const [activeSidebar, setActiveSidebar] = useState(1);
    
    // and so on 

and I'm using @P5-wrapper/react as a p5 wrapper.

I have a canvas component:

const Canvas = memo(({ sketchDimensions, setSketchDimensions, selectedSegment, setSelectedSegment, activeSidebar, selectedView, currentView }) => {
    if (sketchDimensions.length > 0) {
        console.log('initialized canvas');

        return (
            <ReactP5Wrapper
                sketch={shoeSketch}
                sketchDimensions={sketchDimensions}
                setSketchDimensions={setSketchDimensions}
                selectedSegment={selectedSegment}
                setSelectedSegment={setSelectedSegment}
                // and others
            />
        );
    }
});

and problem appears when the state changes and it creates new canvas elements and GPU increases around 0.8-0.9GB every time one of the states change.

task manager

is it possible not to re-render the canvas every time state changes?

I have written it also on 463, but they mentioned I might try it on p5 issues.

nijatmursali avatar Sep 22 '24 07:09 nijatmursali

you can try memo.

thejon07 avatar Sep 22 '24 14:09 thejon07

It looks like re-rendering the canvas is part of the P5-wrapper library's behaviour. There are two sort of different directions you could go in:

  1. Keeping the re-rendering behaviour, figuring out why your memory keeps going up even when the library calls .remove() on your old sketch
  2. Working around the library's behaviour to not rerender

For (1), it might help if you had more code you can share about what your sketch is doing.

For (2), if you're interested in not recreating the canvas every time, I would suggest not changing the state you pass into P5-wrapper. Instead, try updating the data read by the sketch itself, e.g. with useRef, and pass p5 the ref. You can then edit the ref's .current property, and your sketch can continue to read that property as well and get updated values each frame. For something like the sketch size, I would keep passing P5-wrapper the original size so it never rerenders, and instead call p5.resizeCanvas(...) in your sketch's code when a ref value changes.

davepagurek avatar Sep 23 '24 00:09 davepagurek

Closing this now as it's mostly something to be solved in one's own sketch rather than in p5.

davepagurek avatar Oct 30 '24 13:10 davepagurek