Created
May 9, 2018 09:40
-
-
Save carlrosell/ea89410385afd290b00bed958478f2e7 to your computer and use it in GitHub Desktop.
getColorForPercentage.js
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
const isBiggerThan = (value) => (a) => a > value; | |
const getColorForPercentageFunction = (colorList) => { | |
const colors = colorList.sort((a, b) => a.value - b.value); | |
return ((value) => { | |
const foundIndex = colors.map((a) => a.value).findIndex(isBiggerThan(value)); | |
const index = foundIndex !== -1 ? foundIndex : colors.length - 1; | |
const lower = colors[index - 1]; | |
const upper = colors[index]; | |
const range = upper.value - lower.value; | |
const upperValue = (value - lower.value) / range; | |
const lowerValue = 1 - upperValue; | |
const color = { | |
r: Math.floor(lower.color.r * lowerValue + upper.color.r * upperValue), | |
g: Math.floor(lower.color.g * lowerValue + upper.color.g * upperValue), | |
b: Math.floor(lower.color.b * lowerValue + upper.color.b * upperValue) | |
}; | |
return `rgb(${color.r}, ${color.g}, ${color.b})`; | |
}) | |
} | |
/* | |
color: rgb(255, 59, 71); | |
color: rgb(255, 193, 0); | |
color: rgb(0, 215, 66); | |
*/ | |
const myColors = [ | |
{ value: 0.0, color: { r: 0, g: 0, b: 0 } }, | |
{ value: 0.8, color: { r: 255, g: 59, b: 71 } }, | |
{ value: 0.9, color: { r: 255, g: 193, b: 0 } }, | |
{ value: 1.0, color: { r: 0, g: 215, b: 66 } } | |
]; | |
const colorFunction = getColorForPercentageFunction(myColors); | |
function updateTextInput(val) { | |
const elem = document.getElementById('cool'); | |
elem.innerHTML = `${val}%`; | |
elem.style.backgroundColor = colorFunction(val / 100); | |
} | |
updateTextInput(50); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment