Created
December 28, 2021 23:31
-
-
Save exiguus/7ca5897e441b973944811c8813e1844e to your computer and use it in GitHub Desktop.
Generate HSL or RGB colors
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
export function getRandomInt(min: number, max: number): number { | |
min = Math.ceil(min) | |
max = Math.floor(max) | |
return Math.floor(Math.random() * (max - min) + min) | |
} | |
const getRandomRGBColors = (count = 16) => { | |
const colors: [number, number, number][] = [] | |
const ranges = [255, 192, 128, 64, 32] | |
for (let i = 0; i < ranges.length; ) { | |
for (let j = 0; j < ranges.length; ) { | |
for (let k = 0; k < ranges.length; ) { | |
const r = ranges[i] | |
const g = ranges[j] | |
const b = ranges[k] | |
// if the rgb value is not white push the color | |
if (r + g + b !== 3 * 255) { | |
colors.push([ranges[i], ranges[j], ranges[k]]) | |
} | |
k++ | |
} | |
j++ | |
} | |
i++ | |
} | |
return colors | |
} | |
// HSL | |
// S (saturation) and L (lightness) are percentages. 100% saturation is completely saturated, while 0% is completely unsaturated (gray). 100% lightness is white, 0% lightness is black, and 50% lightness is “normal.” | |
// A (alpha) can be a <number> between 0 and 1, or a <percentage>, where the number 1 corresponds to 100% (full opacity). | |
// H (hue) see: https://drafts.csswg.org/css-color/#the-hsl-notation | |
const getRandomHSLColor = (saturation = '20%', alpha = '80%') => { | |
const hue = `${getRandomInt(0, 360)}deg` | |
return [hue, saturation, alpha] | |
} | |
const getRandomHSLColors = (count = 99, saturation = '20%', alpha = '80%') => { | |
const colors = [] | |
for (let i = 0; i < count; i++) { | |
colors.push(getRandomHSLColor(saturation, alpha)) | |
} | |
return colors | |
} | |
export function getRandomColor(): [string, string, string] { | |
const colors = getRandomHSLColors() | |
const max = colors.length - 1 | |
const min = 0 | |
const [hue, saturation, alpha] = colors[getRandomInt(min, max)] | |
return [hue, saturation, alpha] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment