0

Plss tell me whats the error in this code here i am not getting background colour even when mouse is pressed , i am supposed to get alternatively black and green when mouse is pressed function mousePressed() is not executing

var on = false;

function setup() {
  createCanvas(600, 400);
}

function draw() {
  if (on) {
    if (mouseIsPressed) {
      background(0, 255, 0);
    } else {
      background(0);
    }
  }

  background(0);
  stroke(255);
  strokeWeight(4);
  noFill();

  if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
    fill(255, 0, 200);
  }

  rectMode(CENTER);
  rect(300, 200, 100, 100);

  function mousePressed() {
    if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
      on = !on;
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41

1 Answers1

2

There were two issues with your code:

  1. The mousePressed() event handler function was declared inside the draw function instead of globally.
  2. You were always calling background(0) after the if block that would sometimes call background(0, 255, 0) which meant that the background would always be black regardless of what happened in the initial if block.

var on = false;

function setup() {
  createCanvas(600, 400);
}

function draw() {
  if (on) {
    if (mouseIsPressed) {
      background(0, 255, 0);
    } else {
      background(0);
    }
  } else {
    background(0);
  }

  // This would re-draw the background black regardless of what happened above
  // background(0);
  stroke(255);
  strokeWeight(4);
  noFill();

  if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
    fill(255, 0, 200);
  }

  rectMode(CENTER);
  rect(300, 200, 100, 100);
}

// This used to be declared inside the draw() function. Event handlers in p5.js need to be declared globally
function mousePressed() {
  if (mouseX > 250 && mouseX < 350 && mouseY > 150 && mouseY < 250) {
    on = !on;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41