Draw elements in foreground vs background

Hi all,

I’m working with p5js on a shared drawing canvas where 2 people can collaborate on a drawing. I want to draw stars on the canvas that cannot be drawn over. I’m having trouble figuring out if this can be done. I cannot redraw the background because that will clear the things that people have drawn. I don’t want to save what people have drawn in an array as that causes a lot of lag.

I just was wondering if there is a a quality I can give to the star objects that will make them not be able to be drawn over, so they at least appear in the foreground… Any suggestions are appreciated!

When you draw pixel by pixel you could check if the color already present in this pixel is the color of a star. If so don’t draw the new pixel.

You could also have the stars drawn once on an additional PGraphics and perform the pg.get(mouseX,mouseY); check there. (Then the user can also use the stars color but it can still be changed later.)

1 Like

I’m not a hundred percent sure what you’re after, but as @Chrisir said you can use another PGraphics object as a secondary screen/buffer to draw too. It’s the same as drawing to the default one except you have to explicitly mention the instance and call beginDraw() and endDraw() on it yourself.


PGraphics g;

void setup() {
    g = createGraphics(800, 600);

void draw() {
    // ... do some drawing here ...

Then you can just draw the whole thing over the main screen before or after, or use it as some kind of mask.

If you just want a static background or foreground just store the needed data in static variables and always draw it before or after everything else.


I was just referring to pg to use it as an invisible pg to check the mouse against its colors.

But now that you mentioned it: we could also make a transparent pg with stars (not transparent) and place it as a layer on top of the screen

hmm, when I try writing g.beginDraw(): I get an error:
sketch.js:67 Uncaught TypeError: pg.beginDraw is not a function

is there a library i need to include?

upon some googling I see that this is used in processing, but I forgot to mention Im using p5js


Ah. See pages linked from the section on the above page.

You still need the createGraphics bit, but I guess there’s no equivalent set of enclosing calls. Processing is largely an API/Library that wraps core functionality of Java, or in this case javascript.

Don’t forget to call the functions appropriately though.


is different than:


The former affects the main drawing area, the Canvas, whereas the latter affects g, which is a kind of offscreem drawing buffer.