EN
TypeScript - generate random hex color
0 points
In this article, we would like to show you how to generate random hex colors using TypeScript.
Quick solution:
xxxxxxxxxx
1
const randomColor = (): string => {
2
let result = '';
3
for (let i = 0; i < 6; ++i) {
4
const value = Math.floor(16 * Math.random());
5
result += value.toString(16);
6
}
7
return '#' + result;
8
};
In this example, you can see generated color code in hex with preview.
xxxxxxxxxx
1
const randomColor = (): string => {
2
let result = '';
3
for (let i = 0; i < 6; ++i) {
4
const value = Math.floor(16 * Math.random());
5
result += value.toString(16);
6
}
7
return '#' + result;
8
};
9
10
11
// Usage example:
12
13
console.log(randomColor());
14
console.log(randomColor());
15
console.log(randomColor());
Example output:
xxxxxxxxxx
1
#d5af2c
2
#396391
3
#01b8a7
1. The below solution uses predefined digits that compose hex color.
xxxxxxxxxx
1
const DIGITS: string = '0123456789ABCDEF';
2
3
const randomColor = (): string => {
4
let result = '';
5
for (let i = 0; i < 6; ++i) {
6
const index = Math.floor(16 * Math.random());
7
result += DIGITS[index];
8
}
9
return '#' + result;
10
};
11
12
console.log(randomColor());
13
console.log(randomColor());
14
console.log(randomColor());
Example output:
xxxxxxxxxx
1
#CCAD03
2
#15123A
3
#EBDE9B
2. One random number solution
xxxxxxxxxx
1
const randomColor = (): string => {
2
const dec = Math.floor(0x1000000 * Math.random()); // 0x1000000 = 0xFFFFFF + 1
3
let hex = dec.toString(16);
4
for (let i = hex.length; i < 6; ++i) {
5
hex = '0' + hex;
6
}
7
return '#' + hex;
8
};
9
10
console.log(randomColor()); // #c68362
11
console.log(randomColor()); // #1c4bcc
12
console.log(randomColor()); // #4c2be3
Output:
xxxxxxxxxx
1
#c68362
2
#1c4bcc
3
#4c2be3