Learn creative coding writing simple programs
143. Using PGraphics as layers in Processing
By default all the Processing drawing functions draw immediately in your main display. What would happen if you wanted to draw something behind other objects? You would probably need something called PGraphics.
So far you have used always one PGraphics, the default one. So you probably did not even think it existed. But you can create more than one, which allows you to draw things on different virtual displays, and later draw those virtual displays on the main one.
One thing you can do with PGraphics is layers. You can draw different kinds of objects on different layers, and then place them in your display in the order you want. For example texts always in front, rectangles behind. Or small objects in front and big ones behind. You set the rules.
PGraphics have many uses. One other thing you could do is to create a PGraphics larger than the main display, and then move through it using the mouse or your keyboard, like it happens in online maps or computer games. That would be like having your eyes close to a painting, and moving your head to explore different parts of that painting.
In the next episode we will use an array of PGraphics to create an animated loop drawing program.
How to use PGraphics:
1. You declare a variable using the PGraphics type (not int, not float).
2. You initialize the variable using createGraphics(width, height).
3. You use drawing functions on your variable: mygraphics.beginDraw(); mygraphics.ellipse(10,10,10,10); mygraphics.endDraw();
Don't forget to add beginDraw() and endDraw() before and after your drawing functions, or it won't work.
Code editor
background
createGraphics
draw
fill
height
image
int
PGraphics
random
rect
setup
size
text
void
width
Try to stay close to the topic of this episode. Use the Processing forums for help with unrelated Processing projects (or hire me for help ;-)
To indicate that a word in your comment is code, use the `backtick`. Example
Do `float` and `int` smell similar?
To highlight code blocks, surround it with ``` code-fences ``` like this:``` void setup() { size(600, 600); } ```