Show different text depending upon condition

hello all,

how can I write p5 code that shows different text depending upon if condition? here is an example code that I wrote but the text just shows momentarily and disappears once the mouse click is done…

let state;

function setup() {
  createCanvas(400, 400);
  b = createButton('click me');
  b.mouseClicked(showText);
}

function draw() {
  background(220);
}

function showText(){
  state = ~state;
  if(state){
       text('Hi',80,60);
     }
  else{
    text('bye',80,60);
  }
}

thank you

1 Like

The problem here is that draw() is being called repeatedly and each time it is called in fills the entire canvas with light gray. The showText() function only runs once when the button is clicked, so the text will flash for a single frame and then vanish. One option you have is to disable looping and only manually trigger a draw when the button is clicked:

let state;

function setup() {
  createCanvas(400, 400);
  b = createButton("click me");
  b.mouseClicked(showText);
  // Disable automatic execution of draw()
  noLoop();
}

function draw() {
  // This will happen once when setup() completes and then only when redraw() is called after that
  background(220);
}

function showText() {
  state = ~state;
  // Clear the canvas
  redraw();
  if (state) {
    text("Hi", 80, 60);
  } else {
    text("bye", 80, 60);
  }
}

If you want to preserve the looping calls to draw(), which would be necessary if you wanted to have other animated elements, then you could move the text drawing into the draw function:

let state;

function setup() {
  createCanvas(400, 400);
  b = createButton("click me");
  b.mouseClicked(showText);
}

function draw() {
  background(220);

  // Wait until the button is clicked for the first time before we draw any text
  if (state !== undefined) {
    if (state) {
      text("Hi", 80, 60);
    } else {
      text("bye", 80, 60);
    }
  }
}

function showText() {
  state = ~state;
}
3 Likes

Thanks
tested and good to go
:+1: