Mix 2d and 3d drawings

Hi @KelvinLamptey ,

Welcome to the forum! :wink:

Drawing 2d shapes in 3d mode is not specific to Android so the following code also works in Processing Java.

In order to do that, you need to draw your 3d shapes on a separate PGraphics() buffer that you can then display on your 2D canvas. Doing the opposite doesn’t work since drawing an image in 3d space is going to intersect with the 3d shapes you draw.

float angle = 0;

PGraphics canvas3D;

void setup() {
  size(300, 300, P2D);
  canvas3D = createGraphics(width, height, P3D);
}

void draw() {
  background(255);
  
  // 3D shape on a separate PGraphics
  canvas3D.beginDraw();
  canvas3D.background(255);
  
  canvas3D.translate(width / 2, height / 2);
  canvas3D.rotateX(QUARTER_PI * sin(angle));
  canvas3D.rotateY(PI / 3 * cos(angle));
  
  canvas3D.fill(0, 255, 0);
  canvas3D.box(100);
  
  canvas3D.endDraw();
  
  // Display 3D buffer
  image(canvas3D, 0, 0);
  
  // 2D shapes
  fill(255, 0, 0);
  translate(width / 2, height / 2);
  circle(-50, 0, 50);
  circle(50, 0, 50);
  circle(0, -50, 50);
  circle(0, 50, 50);
  
  angle += 0.05;
}

Which gives :

2d3d

Note that you must use P2D with P3D because they are compatible.

See the documentation on the renderers available in Processing :

The renderer parameter selects which rendering engine to use. For example, if you will be drawing 3D shapes, use P3D . In addition to the default renderer, other renderers are:

P2D (Processing 2D): 2D graphics renderer that makes use of OpenGL-compatible graphics hardware.

P3D (Processing 3D): 3D graphics renderer that makes use of OpenGL-compatible graphics hardware.

1 Like