Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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.4.1/p5.js"></script>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!