Last active
August 26, 2021 14:07
-
-
Save ValentaTomas/7c3b7a8f65efd650af379c056f0bd36a to your computer and use it in GitHub Desktop.
Get random bright color in HEX format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function randomDiscreteNumber(max: number) { | |
return Math.floor(Math.random() * max) + 1 | |
} | |
export function getRandomColor() { | |
// Use HSL model to create pastel colors. | |
// It is easier to do that by randomizing hue while keeping saturation and lightness in reasonable boundaries. | |
const hue = 6 * randomDiscreteNumber(60) | |
const saturation = 80 + 10 * Math.random() | |
const lightness = (60 + 10 * Math.random()) / 100 | |
// Convert the HSL model to HEX model. | |
const a = saturation * Math.min(lightness, 1 - lightness) / 100 | |
const f = (n: number) => { | |
const k = (n + hue / 30) % 12 | |
const color = lightness - a * Math.max(Math.min(k - 3, 9 - k, 1), -1) | |
return Math.round(255 * color).toString(16).padStart(2, '0') | |
} | |
return `#${f(0)}${f(8)}${f(4)}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment