
創建給定顏色的相反顏色
在這個問題中,目標是產生與給定顏色相反的顏色顏色。相反的顏色是指暗/亮的方面。例如,如果給定的顏色是黑色,則相反的顏色將為白色。
要建立此相反的顏色,需要一個名為 create_opp_color() 的函數。該函數應接受當前顏色作為參數並傳回相反的顏色。以下是完成此任務的方法:
函數實作:
-
將十六進位轉換為RGB: 假定給定顏色為十六進位格式。首先,將其轉換為 RGB 分量。
-
反轉顏色分量:反轉 R、G 和 B 分量的值(從 255 中減去)。
-
將反轉分量轉換為十六進位:將每個反轉分量轉換回十六進位
-
填滿反轉組件:每個十六進位元件都應該用零填充,以確保它是2 位元十六進位值。
-
重建十六進位顏色字串: 連接填滿的 HEX 元件以形成相反的顏色string.
JavaScript中的實作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | function create_opp_color(currentColor) {
if (currentColor.indexOf( '#' ) === 0) {
currentColor = currentColor.slice(1);
}
if (currentColor.length === 3) {
currentColor = currentColor.repeat(2);
}
const rgb = hexToRgb(currentColor);
const invertedRgb = {
r: 255 - rgb.r,
g: 255 - rgb.g,
b: 255 - rgb.b
};
const invertedHex = rgbToHex(invertedRgb);
return '#' + invertedHex;
}
function rgbToHex(rgb) {
let hex = '' ;
for ( const key in rgb) {
if (rgb.hasOwnProperty(key)) {
const component = rgb[key].toString(16);
hex += component.length === 1 ? '0' + component : component;
}
}
return hex;
}
function hexToRgb(hex) {
let rgb = {};
[ 'r' , 'g' , 'b' ].forEach((key, i) => {
rgb[key] = parseInt(hex. substr (i * 2, 2), 16);
});
return rgb;
}
|
登入後複製
進階技術:
如果您需要更多對比度,您可以根據原始顏色的亮度使用黑色或白色作為相反顏色。這是一個修改後的函數來執行此操作:
1 2 3 4 5 6 7 8 9 10 11 12 | function create_opp_color(currentColor) {
if (currentColor.indexOf( '#' ) === 0) {
currentColor = currentColor.slice(1);
}
if (currentColor.length === 3) {
currentColor = currentColor.repeat(2);
}
const rgb = hexToRgb(currentColor);
const brightness = Math. round ((rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114) / 255 * 100);
return brightness > 50 ? '#000000' : '#FFFFFF' ;
}
|
登入後複製
現在,使用此函數,您可以輕鬆生成任何給定顏色的相反顏色,無論它是亮還是暗。
以上是如何產生給定顏色的相反顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!