如何決定給定顏色的補色
目標是產生與給定顏色相反的顏色。例如,如果當前顏色是黑色,則相反的顏色應該是白色。當為具有動態色彩的文字設定對比背景色以確保清晰可見時,此任務至關重要。
為了實現這一點,我們採用以下方法:
以下程式碼實作此方法:
function invertColor(hex) { 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.'); } // Invert color components. var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16), g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16), b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16); // Pad each component with leading zeros and return. return '#' + padZero(r) + padZero(g) + padZero(b); } function padZero(str, len) { len = len || 2; var zeros = new Array(len).join('0'); return (zeros + str).slice(-len); }
範例輸出:
具有「bw」選項的高階版本可讓您指定結果是否應該更接近黑色或白色,提供更好的對比度以提高可讀性:
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.'); } var r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16); if (bw) { // Formula to determine if the color is closer to black or white. 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 component with leading zeros and return. return '#' + padZero(r) + padZero(g) + padZero(b); }
範例輸出:
[](https: //stackshare.io/resources/color-contrast-checker)
以上是如何找到給定十六進位代碼的補色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!