TypeScript封裝一個根據背景色顯示適合的字體顏色
方法一
在TypeScript中,你可以創建一個函數來確定基于背景顏色的對比色(通常是黑色或白色)作為文本顏色,以確保文本的可讀性。為了計算背景顏色與黑白之間的對比度,我們可以使用Web內容可訪問性指南(WCAG)的公式。
下面是一個簡單的TypeScript函數示例,它接受一個背景顏色(十六進制格式)作為輸入,然后返回一個推薦的字體顏色(黑色或白色):
function getContrastYIQ(hexcolor: string): string {
// 如果輸入不帶#,則添加
if (hexcolor.indexOf('#') !== 0) {
hexcolor = '#' + hexcolor;
}
// 去除#號
hexcolor = hexcolor.replace('#', '');
// 將十六進制顏色分解為r, g, b
const r = parseInt(hexcolor.substr(0, 2), 16);
const g = parseInt(hexcolor.substr(2, 2), 16);
const b = parseInt(hexcolor.substr(4, 2), 16);
// 使用YIQ方程式計算亮度
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
// 根據亮度返回黑色或白色
return yiq >= 128 ? 'black' : 'white';
}
// 用法示例
const backgroundColor = '#005A31'; // 深綠色
const textColor = getContrastYIQ(backgroundColor);
console.log(textColor); // 應該返回'white'因為深綠色背景下白色文本更可讀
這個函數使用了YIQ色彩空間,這是一個電視廣播領域使用的色彩空間,其中Y代表亮度分量,而I和Q分別代表色度分量。在這個例子中,我們只關心Y分量(亮度),以決定文本顏色使用黑色還是白色。
請確保輸入的顏色格式正確,并且你的應用可以處理不同的輸入格式。上面的代碼假設輸入是一個六位的十六進制顏色值。
此外,還有更復雜的方法來判斷對比度,比如根據WCAG 2.0標準計算顏色之間的對比度比率。這樣的計算會更復雜一些,但也可以提供更精確的結果。
方法二
如果你希望函數能夠返回除黑白之外的其他顏色作為字體顏色,你可以通過定義一組顏色和它們的亮度閾值來實現。這樣,函數就可以根據背景顏色的亮度來選擇一個合適的字體顏色。
首先,我們定義一個簡單的亮度判斷函數,然后基于背景色的亮度選擇合適的字體顏色。這里舉例說明如何擴展前面的函數以支持多種顏色選擇。
function getBrightness(hexcolor: string): number {
// 標準化十六進制格式
if (!hexcolor.startsWith('#')) {
hexcolor = '#' + hexcolor;
}
// 提取RGB組件
const r = parseInt(hexcolor.substring(1, 3), 16);
const g = parseInt(hexcolor.substring(3, 5), 16);
const b = parseInt(hexcolor.substring(5, 7), 16);
// 計算亮度
return ((r * 299) + (g * 587) + (b * 114)) / 1000;
}
function chooseTextColor(backgroundHex: string): string {
// 定義顏色選項和它們的亮度界限
const colors = [
{ color: '#000000', minBrightness: 0, maxBrightness: 180 }, // 黑色
{ color: '#FFFFFF', minBrightness: 180, maxBrightness: 256 }, // 白色
{ color: '#FFD700', minBrightness: 100, maxBrightness: 220 }, // 金色
{ color: '#0000FF', minBrightness: 50, maxBrightness: 150 } // 藍色
];
// 獲取背景色亮度
const backgroundBrightness = getBrightness(backgroundHex);
// 選擇一個亮度合適的顏色
const suitableColor = colors.find(c => backgroundBrightness >= c.minBrightness && backgroundBrightness < c.maxBrightness);
return suitableColor ? suitableColor.color : '#FFFFFF'; // 默認返回白色
}
// 用法示例
const backgroundColor = '#005A31'; // 深綠色
const textColor = chooseTextColor(backgroundColor);
console.log(textColor); // 根據配置,可能返回不同顏色
在這個例子中,我為函數增加了幾種顏色選擇。函數chooseTextColor將檢查背景顏色的亮度,并找到一個在設定亮度范圍內的顏色作為文本顏色。你可以根據需要調整顏色選項和它們的亮度界限。