Search code examples
javascriptarraysrandomp5.js

How can I use same random background color to fill rectangle in P5js


I'm trying to do something in P5js. For this, I need to pick random color of an array for background that has to be in setup. Then I want to pick this random selected background color to fill rectangle under draw function.

There are other shapes with randomness under background that has to be run once. And there is another object under rectangle that has to be in a loop. That is why one is in setup and other one is under the draw function. But, I'm going to simplify my problem as:

function setup() {
  createCanvas(400, 400);
  colorsPaletteSecond = [color(0, 0, 0),
                         color(160, 57, 164),
                         color(93, 94, 198),
                         color(135, 198, 112), ];            
  let screenColor = random(colorsPaletteSecond);
  background(screenColor);
}

function draw() {
  stroke(0)
  fill(screenColor);
  rect(200,200,100,100);
}

I need to define screenColor in the draw section as well, to get the same color as the background. Any suggestions?


Solution

  • Simply move let screenColor to the shared scope so that it's accessible from both functions:

    let screenColor;
    
    function setup() {
      createCanvas(400, 400);
      const colorsPaletteSecond = [
        color(0, 0, 0),
        color(160, 57, 164),
        color(93, 94, 198),
        color(135, 198, 112),
      ];
      screenColor = random(colorsPaletteSecond);
      background(screenColor);
    }
    
    function draw() {
      stroke(0);
      fill(screenColor);
      rect(200, 200, 100, 100);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>