From 5e819bfefecada8233df520da3c1fce08686c41c Mon Sep 17 00:00:00 2001 From: Nathan Date: Sun, 20 Oct 2024 20:59:33 +0100 Subject: [PATCH] Contrast the text colour for colourCosts icons --- public/board.js | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/public/board.js b/public/board.js index fc412f9..77ff5f4 100644 --- a/public/board.js +++ b/public/board.js @@ -348,7 +348,8 @@ class Board{ let fontSize = (width*10/cardWidth)*10; // 10 = baseFontSize of 10pt // ^ calced with the width of the card overall context.font = fontSize+"pt Arial"; - context.fillStyle = "#FFF"; + // Get a constrating B/W to the background and set text to that + context.fillStyle = invertColour(fill, true); // Center the text (cost) within the shape this.printCenterText(colour[1], positionX, positionY + height*totalColours); // Reset context stylings @@ -1538,3 +1539,35 @@ function echoCardsInDeck(playerId){ console.log(deckList); } +// https://stackoverflow.com/a/35970186 +function invertColour(hex, bw = true) { + // Split the hex code into individual alphanumerics + if (hex.indexOf('#') === 0) { + hex = hex.slice(1); + } + + // convert 3-digit hex to 6-digits. + if (hex.length === 3) { + hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; + } + if (hex.length !== 6) { throw new Error('Invalid HEX colour.'); } + + let r = parseInt(hex.slice(0, 2), 16), + g = parseInt(hex.slice(2, 4), 16), + b = parseInt(hex.slice(4, 6), 16); + + // Make it black/white for contrast (typical behaviour here) + if (bw) { + // https://stackoverflow.com/a/3943023/112731 + return (r * 0.299 + g * 0.587 + b * 0.114) > 186 + ? '#000000' : '#FFFFFF'; + } + + // Invert colour components + r = (255 - r).toString(16); + g = (255 - g).toString(16); + b = (255 - b).toString(16); + // Pad each with zeros and return + return "#" + padZero(r) + padZero(g) + padZero(b); +} +