Created
October 19, 2016 14:07
-
-
Save michaeljota/e5ed3ac4157209634b230c0454680c1d to your computer and use it in GitHub Desktop.
A simple random hex color generator.
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
interface IColorGradient { | |
min: number; | |
max: number; | |
}; | |
interface IDefaultGradients { | |
red?: IColorGradient; | |
green?: IColorGradient; | |
blue?: IColorGradient; | |
} | |
let defaultGradientsValues: IDefaultGradients = { | |
red: { | |
min: 25, | |
max: 225, | |
}, | |
green: { | |
min: 25, | |
max: 225, | |
}, | |
blue: { | |
min: 25, | |
max: 225, | |
}, | |
}; | |
function getRandomColorsArray(amount = 100, colorGradient?: IDefaultGradients) { | |
colorGradient = Object.assign(defaultGradientsValues, colorGradient); | |
let colorAmount = Math.ceil(Math.cbrt(amount)); | |
let colors = []; | |
let red = getGradienArray(colorGradient.red, colorAmount); | |
let green = getGradienArray(colorGradient.green, colorAmount); | |
let blue = getGradienArray(colorGradient.blue, colorAmount); | |
while (colors.length < amount) { | |
let color = '#' + | |
red[Math.floor(Math.random() * colorAmount)] + | |
green[Math.floor(Math.random() * colorAmount)] + | |
blue[Math.floor(Math.random() * colorAmount)]; | |
if (colors.indexOf(color) === -1) { | |
colors.push(color); | |
} | |
} | |
return colors; | |
} | |
function getGradienArray(gradient: IColorGradient, colorAmount: number): number[] { | |
let color = []; | |
let step = gradient.max - gradient.min / colorAmount; | |
for (let i = gradient.min; i < gradient.max; i += step) { | |
color.push(i.toString(16)); | |
} | |
return color; | |
} | |
let colors = getRandomColorsArray(); | |
console.log(colors); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment