Created
May 25, 2021 17:23
-
-
Save joshzcold/1dbef9c523f8511e2450a0f4fe989e68 to your computer and use it in GitHub Desktop.
Javascript generate random appealing colors
This file contains hidden or 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
/* | |
* Generate appealing random colors using HSV | |
* https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ | |
*/ | |
// needed to keep colors random from each other | |
const golden_ratio_conjugate = 0.618033988749895 | |
// using hsb create perdictable rgb values | |
function hsv_to_rgb(h, s, v){ | |
h_i = parseInt(h*6) | |
let f = h*6 - h_i | |
let p = v * (1 - s) | |
let q = v * (1 - f*s) | |
let t = v * (1 - (1 - f) * s) | |
let r = g = b = 0 | |
if(h_i === 0 ) { r = v; g = t; b = p } | |
if(h_i === 1 ) { r = q; g = v; b = p } | |
if(h_i === 2 ) { r = p; g = v; b = t } | |
if(h_i === 3 ) { r = p; g = q; b = v } | |
if(h_i === 4 ) { r = t; g = p; b = v } | |
if(h_i === 5 ) { r = v; g = p; b = q } | |
return `rgba(${parseInt(r*256)}, ${parseInt(g*256)}, ${parseInt(b*256)}, 1)` | |
} | |
// call hsv_to_rgb using random value + hue and saturation | |
function generate_random_color( ){ | |
let rand = Math.random() | |
let h = rand + golden_ratio_conjugate | |
h %= 1 | |
return hsv_to_rgb(h, 0.3, 0.99) | |
} | |
console.log(generate_random_color()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment