I’m trying to clear pixels in PGraphics object. It’s not working? or am I missing something? Here’s a little code for illustration.
PGraphics pg;
void setup() {
size(600, 600);
background(0);
fill(255);
stroke(255);
pg = createGraphics(width, height);
}
void draw() {
// Create random cirles on canvas
ellipse(random(width), random(height), 5, 5);
if (mousePressed)
{
// Create a line from origin to mouse cursor on seperate canvas
pg.beginDraw();
pg.clear();
pg.stroke(255);
pg.line(0, 0, mouseX, mouseY);
pg.endDraw();
image(pg, 0, 0);
}
}
If I only want one line as I move my mouse around, how would I achieve that? I can’t use background(0) in draw method because it will erase everything.
I have tried pg.background(0, 0) and it still won’t work.
In the main draw() method add the the statement background(0) as the first statement. It will now give you the single line but erases the old stars causing them to flicker.
To correct that either
create another PGraphics for the stars or
remember the position of each star and draw them all every frame
Thanks for the ideas. I was able to achieve it by drawing my line to the main canvas and circles on PGraphics. Kinda switched them. Now my code looks like this
void draw() {
background (0);
// Create random cirles on canvas
pg.beginDraw();
pg.ellipse(random(width), random(height), 5, 5);
pg.endDraw();
image(pg, 0, 0);
// Create line from origin to cursor
if (mousePressed)
{
line(0, 0, mouseX, mouseY);
}
}
But question still remains, how to use clear function?
Is there a way to completely reset PGraphics object?
(I don’t want to create another instance on each frame)
Alright I found this issue on GitHub which explains how PGraphics actually work.
So it turns out that PGraphics is an off-screen canvas and we are using Image() function to draw everything that is in PGraphics to the main canvas. So basically everything we see is main canvas.
So which is why clear() won’t erase my lines because they are drawn on the main canvas and not PGraphics. It all makes sense now. PGraphics is working as it should. I did not understand it correctly.
I’ll keep this topic as it is, in case if anyone else has the same confusion.
Thanks!