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]
appponent.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 : ponent.ts
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.ponent.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./edit/angular-ivy-kvdhev?file=src%2Fapp%2Fapp.ponent.ts
Share Improve this question asked Aug 5, 2022 at 9:39 EMahan KEMahan K 46711 silver badges29 bronze badges 1-
To start,
this.totalColor.push(color);
should be outside (after) the for loop. You are currently pushing inplete color codes. – juzraai Commented Aug 5, 2022 at 9:43
8 Answers
Reset to default 3- move the
color
variable inside the first loop. - 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)
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))
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.ponent.html',
styleUrls: ['./app.ponent.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);
}
}
}
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.
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
is0xffffff
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 than0x100000
).
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
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));
Here is my answer with some references if you need:
function randomColorsGenerator(length) {
let randomColorsArray = [];
for (let i = 0; i < length; i++) {
let color = Math.random(); // This line generates pseudo-random number that's greater than or equal to 0 and less than 1.
color = Math.random().toString(16); // This line converts number to string but based on 16(0,1,2, ... , E, F).
color = Math.random().toString(16).substring(2, 8).toUpperCase(); // This line extracts the part we need(the first 6 character after character in position 2) and then converts everything to UPPERCASE
randomColorsArray.push(color);// This line adds the generated color to the randomColorsArray
}
console.log(randomColorsArray); // This line prints the randomColorsArray in console
}
randomColorsGenerator(10);
For Math.random() see: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
For toString(16) see: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString#parameters (You should read about "radix")
For substring(x, y) see: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#try_it
For toUpperCase() see: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase#try_it
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744993384a4605041.html
评论列表(0条)