Home > Software design >  How to generate random color in the for loop in javascript
How to generate random color in the for loop in javascript

Time:08-06

Trying to generate randomly html color codes but not working. So, How to generate it in the for loop. I have tried in google and stackoverflow, but not able to find out the solution. If anyone knows please help to find the solution.

Example totalColor should be like ['#CD5C5C','#F08080','#FA8072','#E9967A',.....upto 10]

app.component.ts:

getrandomcolor(length) {
    let letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < length; i  ) {
      color  = letters[Math.floor(Math.random() * 16)];
      this.totalColor.push(color);
    }

    console.log(this.totalColor);
  }

Demo : https://stackblitz.com/edit/angular-ivy-kvdhev?file=src/app/app.component.ts

CodePudding user response:

You have mistake here, you push while getting each hex letter which will be incorrect. Also the hex color length (CSS) should be:

  • 3 (shortand)
  • 6 (RRGGBB)
  • 8 (RRGGBBAA)

Now, in this sample I use regular 6 digit hex code value, to fix it, the color should be added to array after loop:

import { Component, VERSION, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular '   VERSION.major;

  public totalColor = [];

  ngOnInit(): void {
    this.getrandomcolor(10);
  }

  getrandomcolor(length) {
    for(let x = 0; x < length; x  ){
      let letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i  ) {
        color  = letters[Math.floor(Math.random() * 16)];
      }
      console.log(color);
      this.totalColor.push(color);
    }

  }
}


CodePudding user response:

  1. move the color variable inside the first loop.
  2. create a nested for loop inside the first for loop that iterates 6 times, each time concatenating the color string with an new character.

const totalColor = []

function getrandomcolor(length) {
  let letters = '0123456789ABCDEF';

  for (let i = 0; i < length; i  ) {
    let color = '#';
    for (let j = 0; j < 6; j  ) {
      color  = letters[Math.floor(Math.random() * 16)];
    }
    totalColor.push(color);
  }
  console.log(totalColor);
}

getrandomcolor(10)

CodePudding user response:

Check this out

function createRandomString(length) {
  let chars = "0123456789ABCDEF", color="";
  for (let i = 0; i < length; i  ) {
     color  = chars[Math.floor(Math.random() * 16)];
  }
  return '#' color;
}
console.log(createRandomString(6))

CodePudding user response:

Use RGB value like:

function giveRandomColors(NumberofColors) {
  let randomColors = [];
  for (let i = 0; i < NumberofColors; i  ) {
    randomColors.push({
      r: Math.floor(Math.random() * 255),
      g: Math.floor(Math.random() * 255),
      b: Math.floor(Math.random() * 255),
    });
  }
  return randomColors;
}
console.log(giveRandomColors(10));

Hope it helps.

CodePudding user response:

One liner using Array.from:

const generateRandomColors = (amount) => Array.from(
  { length: amount },
  () => '#'   (Math.floor(Math.random() * 16777215))
                .toString(16).toUpperCase()
                .padStart(6, 0)
)

console.log(generateRandomColors(10))
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

Explanation:

  • Math.floor() converts our decimal into integer,
  • 16777215 is 0xffffff in hex. This is our max number that we want to pull,
  • toString(16) converts our pulled number to hex,
  • padStart(6, 0) fills our string with 0 at start, if our pulled number is to small (smaller than 0x100000).

CodePudding user response:

There is already a solution on stackoverflow

export class AppComponent implements OnInit {
  name = 'Angular '   VERSION.major;

  public totalColor: string[] = [];

  ngOnInit(): void {
    this.getrandomcolor(10);
  }

  getrandomcolor(length) {
    for (let i = 0; i < length; i  ) {
      this.totalColor.push(this.randomColor());
    }

    console.log(this.totalColor);
  }

  randomColor(): string {
    return (
      '#'   (0x1000000   Math.random() * 0xffffff).toString(16).substr(1, 6)
    );
  }
}

You can view it on StackBlitz

CodePudding user response:

As per my understanding, You want to get the array of random color codes based on the array length passed as a function parameter. If Yes, You can easily achieve it by creating the 6 char color codes inside the function itself.

Live Demo :

const totalColor = [];

function getrandomcolor(length) {
  let letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < length; i  ) {
    for (let j = 0; j < 6; j  ) {
      color  = letters[Math.floor(Math.random() * 16)];
    }
    totalColor.push(color);
    color = '#';
  }
  return totalColor;
}

console.log(getrandomcolor(10));

  • Related