Implemented a more robust algorithm to select a contrasting color based on distance from the original color.
This commit is contained in:
+17
-6
@@ -401,14 +401,25 @@ function rgbToHex(rgb) {
|
||||
|
||||
function getContrastingColor(hexColor) {
|
||||
const nodeColor = hexToRgb(hexColor);
|
||||
const black = { r: 0, g: 0, b: 0 };
|
||||
const options = [
|
||||
{ name: 'cyan', color: { r: 0, g: 255, b: 255 } },
|
||||
{ name: 'bright pink', color: { r: 255, g: 20, b: 147 } },
|
||||
{ name: 'bright green', color: { r: 0, g: 255, b: 0 } },
|
||||
{ name: 'white', color: { r: 255, g: 255, b: 255 } }
|
||||
];
|
||||
|
||||
// Calculate the color that's 70% away from the node color and 30% away from black
|
||||
const r = Math.round(nodeColor.r * 0.3 + (255 - nodeColor.r) * 0.7);
|
||||
const g = Math.round(nodeColor.g * 0.3 + (255 - nodeColor.g) * 0.7);
|
||||
const b = Math.round(nodeColor.b * 0.3 + (255 - nodeColor.b) * 0.7);
|
||||
let bestColor = options[0];
|
||||
let maxDistance = 0;
|
||||
|
||||
return rgbToHex({ r, g, b });
|
||||
options.forEach(option => {
|
||||
const distance = colorDistance(nodeColor, option.color);
|
||||
if (distance > maxDistance) {
|
||||
maxDistance = distance;
|
||||
bestColor = option;
|
||||
}
|
||||
});
|
||||
|
||||
return rgbToHex(bestColor.color);
|
||||
}
|
||||
|
||||
function colorDistance(rgb1, rgb2) {
|
||||
|
||||
Reference in New Issue
Block a user