Created
November 15, 2016 12:55
-
-
Save danielgindi/1215fd81e7580c89bed27b729ce1fca4 to your computer and use it in GitHub Desktop.
Find the color (out of an array of colors) that is most distant (brightness-wise) to the target color.
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
var getDistantBrightnessColor = (function () { | |
// Calculate grayscale color (luma) according to ITU-R Recommendation BT. 709 | |
var grayscaleLuma709Color = function(color) { | |
return Math.round(0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b) | |
}; | |
var linearDiffColor = function(color1, color2) { | |
return Math.abs(color1.r - color2.r) + | |
Math.abs(color1.g - color2.g) + | |
Math.abs(color1.b - color2.b); | |
}; | |
return function (color, matches) { | |
var distances = []; | |
// Prepare an array of colors with their distances from the target color | |
for (var i = 0; i < choices.length; i++) { | |
distances.push({ | |
color: matches[i], | |
distance: | |
Math.abs(grayscaleLuma709Color(matches[i]) - grayscaleLuma709Color(color)) + | |
linearDiffColor(matches[i], color) | |
}); | |
} | |
// Sort in reverse order, to get the best contrast first | |
distances.sort(function(a, b) { | |
return b.distance - a.distance | |
}); | |
return distances[0].color | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment