r/processing • u/snapkarklepop • 8h ago
Help request drawing program
i’m creating a drawing program within processing and i’m trying to add a way to change the background/canvas color. within the draw function, i have a color wheel that changes the brush color, as well as a color wheel that changes the canvas color. all is going smoothly, except when i try to put it all together. if i draw the canvas within the void setup, the user is unable to change its color. however, if i draw the canvas within the void draw, it redraws itself between every iteration of the brushstroke, so the brush only ever shows up at its current state and never leaves a mark behind.
i think i worded this oddly but hopefully it makes sense. can anybody help me figure out how to allow the canvas color to change while not “erasing” the brush strokes?
3
u/forgotmyusernamedamm 8h ago
There's a couple ways to solve this. The easiest is to use PGraphics. With a pgraphic you can save your painting into an image with no background. Then show that image over a background with a color you can change. Here's sample code.
PGraphics pg;
color bgColor;
void setup() {
size(500, 500);
pg = createGraphics(500, 500);
bgColor = color(200, 100, 20);
}
void draw() {
background(bgColor);
pg.beginDraw();
pg.stroke(0, 200, 100);
pg.strokeWeight(6);
if(mousePressed){
pg.line(mouseX, mouseY, pmouseX, pmouseY);
}
pg.endDraw();
image(pg, 0, 0);
}
void keyPressed(){
if(key == ' '){
bgColor = color(random(255), random(255),random(255));
}
}1
2
u/rusticlypredactious 8h ago
The setup() function is only called once when the program first runs and any variables declared there aren't accessible to other functions. You could store your canvas color as a global variable and then store your input data in an array to be redrawn every frame. Check out this example on the processing site: https://processing.org/examples/storinginput.html
1
u/TurtleGraphics64 5h ago
A few people have written with ways to approach this. You worded it clearly, and your question makes sense. Because you want to change the background but keep the brushstrokes that you had drawn prior to changing the background you'll need to save all of the lines of the brushstrokes into an array. (Or actually, probably two arrays. One for the X-values and one for the Y-values). Basically, you as the mouse moves you should store its mouseX and mouseY location to the arrays. Your draw() function should start by drawing the background color first, then loop through (use a for-loop) your arrays and draw a line from the first two x,y points to the second x,y points stored, then a line from the second x,y points to the third x,y pair, etc until you get to the final x.y pair of points.
1
u/shifty4690 8h ago
I would make a "background rectangle" which will serve as your canvas and will be drawn before anything else. And then instead of changing the canvas color you change the color of your background rectangle.