Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

243
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda