Painting App in Processing with Toggleable Menu

Here's some code to start creating a painting app in Processing. Hold down space to access a future "menu". You may code in a color picker, or other tools in this menu. Press 's' to save your image. It's a very simple framework, but it gives you a good base to start developing your own drawing applications.

Notice how we create a new PGraphics object to draw on, which makes it easy to add other elements to our app without affecting the pixels of the canvas.

// canvas object to draw on
PGraphics canvas;

// menu toggle;
boolean menu = false;

// background color
color bgcolor = color(190);


void setup()
{
size(500, 500);
// create new PGraphics that's the same size as our app
canvas = createGraphics(width, height, P2D);
}


void draw()
{
background(bgcolor);
// if mouse is pressed and the menu isn't on
if (mousePressed && !menu) {
// start canvas drawing
canvas.beginDraw();
// draw a line from the mouse position
canvas.line(mouseX, mouseY, pmouseX, pmouseY);
// end the canvas drawing
canvas.endDraw();
}

// display the canvas object
image(canvas, 0, 0);

// if menu is on, execute menu function
if (menu) {
menu();
}
}


void keyPressed() {
// if spacebar is pressed, toggle menu boolean
if (key == ' ') {
menu = true;
}
// if 's' key is pressed, save image to out.png
if (key == 's') {
canvas.save("out.png");
}
}


void keyReleased() {
// if spacebar is released, toggle menu boolean
if (key == ' ') {
menu = false;
}
}


// menu function
void menu() {
fill(0);
rect (20, 20, 50, 50);
// draw menu here, and do menu functionality
}