Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
How to keep randomizing colors in p5.js?

I just started learning p5.js myself and I have a question with randomizing colors. Right now I see that the color will be reset randomly only when I restart the code. But is it possible to make it happen whenever mouse is pressed?

Here is my code:

let r, g, b; 

function setup() {
  createCanvas(400, 400);
  r = random(255);
  g = random(255);
  b = random(255);
}

function draw() {
  if (mouseIsPressed) {
    fill(r,g,b);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Rabbid76 is right that you need to overwrite the r, g, b variables if your goal is to persist those values after the mouse is released, but I'd suggest doing it inside the mousePressed global function so that multiple triggers won't occur.

let r;
let g;
let b;

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

function draw() {
  fill(r, g, b);
  ellipse(mouseX, mouseY, 80, 80);
}

function mousePressed() {
  randomizeColors();
}

function randomizeColors() {
  r = random(255);
  g = random(255);
  b = random(255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to create new r, g and b values when the mouse is pressed:

let r = 255, g = 255, b = 255; 

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

function mousePressed() {
    r = random(255);
    g = random(255);
    b = random(255);
}

function draw() {
    fill(r, g, b);
    ellipse(mouseX, mouseY, 80, 80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda