Implemented a more robust algorithm to select a contrasting color based on distance from the original color.

This commit is contained in:
Benjamin Arntzen (aider)
2024-06-27 10:34:17 +01:00
parent fd735be762
commit 00a42c257c
+17 -6
View File
@@ -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) {