P5 question

Hii guys,

I’m beginner of P5 and here is my coding question in the remark:

let c = 0;
let bubbleSize = 0;

function setup() {
  background1();
}

function draw() {
  background1();
  bubble();// 
  
}

function keyPressed() {
  if (c == 0) {
    c = c+10}else{c=c+20;if(c>255){c=0}}
}

function doubleClicked(){background(255)} //why this function doesn't work ??

// User defined function 1:

function bubble() {
  strokeWeight(10);
  fill(255, 100,c);
  ellipse(mouseX, mouseY, bubbleSize);
  bubbleSize = abs(mouseX - pmouseX);
}


// User defined function 2:
function background1() {
  createCanvas(800, 800);
  background(216, 203, c);

  strokeWeight(0.5);
  fill(197, 168, 26);
  triangle(200, 0, 140, 90, 250, 110);

  fill(121, 133, 116, 200);
  ellipse(240, 140, 130, 130);

  fill(119, 67, 152);
  ellipse(70, 80, 80, 80);

  strokeWeight(2);
  line(55, 0, 100, 240);

  strokeWeight(1);
  line(0, 80, 200, 80);

  strokeWeight(5);
  line(100, 0, 230, 120);

  strokeWeight(1);
  line(20, 180, 220, 180);

  fill(123, 0, 0);
  strokeWeight(3);
  rect(292, 180, 55, 50);

  line(327, 202, 361, 202);

  strokeWeight(4);
  line(327, 210, 361, 210);
}

Your doubleClicked() function does work! You can prove it by adding a print statement:

function doubleClicked(){
  background(255);
  console.log('double clicked');
}

Now if you double click, you’ll see that message printed to the console. So your function is running correctly.

However, you might be expecting your screen to fill with white because of the background(255) call, but that’s not what happens.

To understand why, think about what happens inside your draw() function:

function draw() {
  background1();
  bubble();
}

Your draw() function runs 60 times per second, and each frame, you call the background1() function:

function background1() {
  createCanvas(800, 800);
  background(216, 203, c);

That function creates a canvas and draws a yellow background.

That means, even if the user double-clicks and your draw a white background, you’re immediately drawing over it with a different background.

To fix this, you might create some variables that keep track of the background color. Then you can change them in your event functions, and use them to draw a background in the draw() function.