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.

Tags: pgraphics, begindraw, enddraw, creategraphics

Code editor

You can make changes to the code below. Then
Below you can ask and answer questions related to this video. If your question is unrelated to the video, please post it at the Processing Forum as I'm unable to help with all of your programs and still have enough free time to eat and sleep :)
comments powered by Disqus