Created
August 25, 2017 18:19
-
-
Save Linnk/7fe6d246d982bf91d343675fb6e156f0 to your computer and use it in GitHub Desktop.
Find a middle color between two colors given.
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
/** | |
* From hex to dec. | |
*/ | |
function hex(hex) | |
{ | |
var result = 0 | |
for (var i = 0; i < hex.length; i++) | |
{ | |
result = result * 16 + '0123456789abcdefgh'.indexOf(hex[i].toLowerCase()); | |
} | |
return result | |
} | |
/** | |
* factor2 needs to be between 0 and 1, to calculate how much of the | |
* two colors you want your middle color. | |
*/ | |
function midcolor(color1, color2, factor2) | |
{ | |
var c1 = color1.replace('#', '').match(/.{1,2}/g) | |
var c2 = color2.replace('#', '').match(/.{1,2}/g) | |
var factor1 = 1 - factor2 | |
var c3 = [ | |
parseInt(hex(c1[0]) * factor1 + hex(c2[0]) * factor2).toString(16), | |
parseInt(hex(c1[1]) * factor1 + hex(c2[1]) * factor2).toString(16), | |
parseInt(hex(c1[2]) * factor1 + hex(c2[2]) * factor2).toString(16), | |
] | |
return '#' + c3.join('') | |
} | |
console.log( | |
midcolor('#f0ad4e', '#5cb85c', 0.5) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment