Home > Software design >  Generate Infinite Colors for Array
Generate Infinite Colors for Array

Time:06-05

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;
        }

CodePudding user response:

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;

CodePudding user response:

define your randomColor directly, replace

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

with

this.color = '#'   Math.floor(Math.random()*16777215).toString(16);
  • Related