Skip to content

Instantly share code, notes, and snippets.

@souporserious
Created November 28, 2016 04:35
Show Gist options
  • Save souporserious/536dff4e3b5eb84d716d57311d6d19d8 to your computer and use it in GitHub Desktop.
Save souporserious/536dff4e3b5eb84d716d57311d6d19d8 to your computer and use it in GitHub Desktop.
create a scale from multiple colors
// mashup
// https://gist.github.com/maxwells/8251275
// https://github.com/andrewbranch/Colorpolate
// convert 6-digit hex to rgb components;
// accepts with or without hash ("335577" or "#335577")
function hexToRgb(hex) {
const [r, g, b] = hex.replace(/#/,'').match(/.{1,2}/g)
return [
parseInt(r, 16),
parseInt(g, 16),
parseInt(b, 16)
]
}
function interpolate(start, end, amount) {
return parseInt(end - (end - start) * amount, 10)
}
function polycolorScale(colors, amount) {
const colorCount = colors.length
const stops = [0]
for (let i = 1; i < colorCount; i++) {
stops[i] = stops[i - 1] + 1 / (colorCount - 1)
}
// const stops = [0, 300, 500]
// convert all colors to rgb
colors = colors.map(color =>
/^#[0-9A-F]{6}$/i.test(color) ? hexToRgb(color) : color
)
// calculate current scale
for (let i = 1; i < stops.length; i++) {
const color = colors[i]
const lastColor = colors[i - 1]
const stop = stops[i]
const laststop = stops[i - 1]
const newColor = []
for (let i = 0; i < 3; i++) {
newColor[i] = interpolate(color[i], lastColor[i], 1 - (stop - amount) / (stop - laststop))
}
return newColor
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment