Created
June 30, 2017 07:49
-
-
Save marcmartino/4b60f318f1794b7e8fcf83519f63153c to your computer and use it in GitHub Desktop.
dynamic color blending
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
//jshint esnext:true | |
// curveColors should have a length longer than or equal to 1 | |
// the colors are split evenly- with a curveColors length of 3 | |
// with said curveColors, a score of 75 would respond to halfway between index 1 and 2 | |
const curveColors = [{r: 49, g: 198, b: 84}, | |
{r: 46, g: 48, b: 193}, | |
{r: 193, g: 138, b: 44}, | |
{r: 193, g: 44, b: 44}] | |
// score should be between 0-100 | |
const score = 50 | |
const colorCalc = { | |
calculateBetweenColors: function (btwnPos, startColorObj, endColorObj) { | |
return ['r', 'g', 'b'].reduce((rgbObj, colorLet) => { | |
const startCol = startColorObj[colorLet] | |
const endCol = endColorObj[colorLet] | |
rgbObj[colorLet] = Math.abs(startCol - endCol) * btwnPos + Math.min(startCol, endCol) | |
return rgbObj | |
}, {}) | |
}, | |
curveColorObj: function (thisScore) { | |
const curveColorPosition = thisScore * ((curveColors.length - 1) / 100) | |
const betweenPosition = curveColorPosition % 1 | |
return this.calculateBetweenColors(betweenPosition, | |
curveColors[Math.floor(curveColorPosition)], curveColors[Math.ceil(curveColorPosition)]) | |
}, | |
curveColor: function (colorObj) { | |
return `rgb(${colorObj.r}, ${colorObj.g}, ${colorObj.b})` | |
} | |
} | |
let bgColor = colorCalc.curveColor(colorCalc.curveColorObj(score)) | |
console.log(bgColor) | |
//document.body.style.backgroundColor = bgColor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment