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

245
Vistas
Generate Infinite Colors for Array

I want to create an array full of random colors, that will never run out to generate random balls with random colors. So instead of having only 5 colors (blue, red, green, yellow, white) to choose from I want a different color for every ball.

whole code:

I have already tried:

var randomColor = Math.floor(Math.random()*16777215).toString(16);

Here I only get one random color for every ball. And I have also used loops already which is probably the right answer but I just implemented it wrongfully.

JS:

var ballArray = [];
var colorArray = ['blue','red','green','yellow','white'];
var gravity = 0.9;

function drawBall() {
    for (var i = 0; i < ballArray.length; i++) {
        var ball = ballArray[i];
        ctx.fillStyle = ball.color;
        ctx.beginPath();
        ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.closePath();
        
        ball.x += ball.xd;
        if (ball.x + ball.radius > screenWidth || ball.x - ball.radius < 0) {
            ball.xd *= -1;
        }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I am not sure if I understand you correctly. Do you want each ball to have a different random color without the color repetition? Or just fix the second JSFiddle code to generate balls with random numbers without the flickering?

If you want to have a unique color for each ball, you can store already used colors in an array and check whether newly generated color is included in the array. For that, I would use this code:

var ballArray = [];
var usedColors = [];
var gravity = 0.9;

function generateNewColor() {
      var letters = '0123456789ABCDEF';
      var colorIncluded = true;

      while (colorIncluded == true) {
        var color = '#';
        // generate new color
        for (var i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        // check if the color is already used
        var used = false;
        for(var i = 0; i < usedColors.length; i++){
          if(usedColors[i] == color){
            used = true;
            break;
          }
        }
        if(!used){ break; }
      }
      usedColors.push(color);
      return color;
}

Nevertheless this method is not very effective for a large amount of generated balls.

To fix the flickering in your code, just erase the function that returns a random number in a Ball() function:

this.color = getRndColor();

And use the generated color in a drawBall() function:

ctx.fillStyle = ball.color;
about 4 years ago · Juan Pablo Isaza Denunciar

0

define your randomColor directly, replace

this.color = colorArray[randomNumber(0, colorArray.length - 1)];

with

this.color = '#' + Math.floor(Math.random()*16777215).toString(16);
about 4 years ago · Juan Pablo Isaza 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