Question about Drawing Application with Background Change and createGraphics()

Hi there. I am teaching an 8th grade creative coding class and I have a few students who are having the same issue that I don’t know how to solve. Any suggestions for how to solve the following coding challenge? :pray:

We are making drawing applications. Students want to be able to draw to a canvas using

line(mouseX, mouseY, pmouseX, pmouseY);

They also want to be able to change the background color without erasing their previous drawing. So I suggested drawing their lines on a createGraphics layer and then changing the background color on the canvas under the createGraphics layer.

But they also want to be able to clear the lines drawn on the createGraphics layer. So when they draw over the createGraphics layer with the background function, they can no longer see the background drawn on the canvas, so they can no longer change the background color.

Here is a paired down sketch that illustrates the problem. Try clicking “Change Background” after clicking “Clear Drawing”.

var drawingCanvas;

function setup() {
  createCanvas(400, 400);
  drawingCanvas = createGraphics(400, 400);
  background(220);
  
  // Change Background Button
  button = createButton("Change Background");
  button.position(0, 0);
  button.mousePressed(changeBG);
  
  // Clear drawing Button
  button = createButton("Clear Drawing");
  button.position(200, 0);
  button.mousePressed(clearDrawing);
}

function draw() {
  
  // Draw the line to the drawingCanvas if mouse is pressed
  if (mouseIsPressed) {
    drawingCanvas.line(mouseX, mouseY, pmouseX, pmouseY);
  }
  
  // Draw the drawingCanvas
  image(drawingCanvas, 0, 0);
}

// If Change Background button is pressed, choose a random background color
function changeBG() {
  background(random(255));
}

// If clearDrawing button is pressed, it erases the drawingCanvas
// If I use drawingCanvas.background(), it draws over the canvas background, so I can't use the Change Background button anymore. 
function clearDrawing(){
  drawingCanvas.background(random(255));
}

clear()

function clearDrawing(){
  drawingCanvas.clear();
  changeBG();
}

Thank you! I knew there must be a simple solution!