Save & Redraw Pixels (quickly)

Is there a way to redraw or save pixels in near constant time?

Currently Im creating a grain overlay by drawing thousands of randomly placed rectangles. I have to draw this grain for every single frame. My issue is that looping through and drawing thousands of rects is time consuming. I was wondering if there is a way to draw my grain overlay once, save the pixel data, and then add the grain in every frame (in a way thats quicker than just re drawing the grain)

Im trying to keep my project small and just code based, so I’de like to find a way to do this without saving the grain as a png.

This may be a stupid question as I have very little knowledge of the backend to p5. I just figured that if I can pre load and re draw images quickly, I should be able to do the same with the canvas without actually making it an image.

Any reply is greatly appreciated!

Create a separate graphics buffer with createGraphics(width, height), draw your grains to that in setup(), draw that graphics object onto your main canvas each frame with image(). This won’t be constant time per se, it will be Ο(n) where n is the number of pixels, so it will have a greater impact on your frameRate given a larger canvas size, but it should be much faster than numerous rect() calls.

4 Likes

Ahh! I have yet to use graphics to my advantage. Thats the answer I needed. Thank you!

1 Like

Hello, @mosacrafts, and welcome to the Processing Forum!

The p5.js: createGraphics() reference page may be of help to you.