'3d Primitives not Rendering correctly when createGraphics is used in p5js and WEBGL

I am trying to write some code that draws a rotating cube on an offscreen graphics window in p5js using WebGL. when I draw the cube directly on the canvas it works fine, but when I try and draw it on the graphics object, it renders incorrectly.

    let canvas2;
function setup() {
  createCanvas(400, 400);
  canvas2 = createGraphics(400,400,WEBGL)
}

function draw() {
  background(220);
  canvas2.background(255);
  canvas2.push();

  canvas2.noFill();
  canvas2.rotateX(0.01*frameCount);
  canvas2.box(50,50,50);
  
  
  image(canvas2,0,0,400,400);
  canvas2.pop();
}

any help would be appreciated



Solution 1:[1]

Unlike the main canvas, p5.Graphics objects do not have their depth buffer automatically cleared for each frame. You can do this manually by calling WebGLRenderingContext.clearDepth on the drawingContext for your p5.Graphics or you can just use the built in p5.js clear() function which will clear the depth buffer and the colors.

let canvas2;
function setup() {
  createCanvas(400, 400);
  canvas2 = createGraphics(400, 400, WEBGL);
}

function draw() {
  background(220);
  
  // This line fixes the issue:
  canvas2.clear();
  
  canvas2.background(255);
  canvas2.push();

  canvas2.noFill();
  canvas2.rotateX(0.01 * frameCount);
  canvas2.box(50, 50, 50);

  image(canvas2, 0, 0, 400, 400);
  canvas2.pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Wheeler