From 00a42c257c3ff40606947bd03824beffcd1a36ab Mon Sep 17 00:00:00 2001 From: "Benjamin Arntzen (aider)" Date: Thu, 27 Jun 2024 10:34:17 +0100 Subject: [PATCH] Implemented a more robust algorithm to select a contrasting color based on distance from the original color. --- public/app.js | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/public/app.js b/public/app.js index 0172e30..07593e3 100644 --- a/public/app.js +++ b/public/app.js @@ -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) {