From d5d0b110a1fdf9db26afd19fb700b1e4517acec0 Mon Sep 17 00:00:00 2001 From: talentestors Date: Fri, 10 May 2024 13:42:49 +0800 Subject: [PATCH] add js/hexColor.js file --- js/hexColor.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 js/hexColor.js diff --git a/js/hexColor.js b/js/hexColor.js new file mode 100644 index 0000000..89afe17 --- /dev/null +++ b/js/hexColor.js @@ -0,0 +1,32 @@ +/* 用于填充字符串 `str` 到指定长度 `len`,默认为 2 +例如:padZero('F', 2) => '0F' */ +function padZero(str, len) { + len = len || 2; + const zeros = new Array(len).join("0"); + return (zeros + str).slice(-len); +} +function invertColor(hex, bw) { + 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 color."); + } + let r = parseInt(hex.slice(0, 2), 16), + g = parseInt(hex.slice(2, 4), 16), + b = parseInt(hex.slice(4, 6), 16); + if (bw) { + // https://stackoverflow.com/a/3943023/112731 + return r * 0.299 + g * 0.587 + b * 0.114 > 186 ? "#000000" : "#FFFFFF"; + } + // invert color 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); +}