說說顏色轉換

前言

在項目中遇到了顏色轉換,所以就研究瞭如何進行顏色轉換,記錄下來方便之後溫故。

十六進制轉換成 RGBA

/** * description: 把十六進制顏色轉化成rgba, 分別有三種, 例如: '#fff' '#ffff00' '#ffff00ff'——注意默認最後兩位爲透明度的rgba * param {type} str爲上面描述的參數 * return: rgba(num, num, num, num) 例如傳入'#ffffff' 傳出rgba(255, 255, 255, 1.00)沒有透明度值默認是1 */
function changeHexToRgba(str) {  
    const REGCOLOR = /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/;  
    const ISRGBA = REGCOLOR.test(str);  
    if (ISRGBA === false) {    
        throw Error("Not a valid value");  
    }  
    // 去掉#號 
    const colorStr = str.slice(1);  
    const len = colorStr.length;  
    if (len === 3) {   
        const color = colorStr
            .split("")
            .map(ele => parseInt(`0x${ele.repeat(2)}`))
            .join(",");
        return `rgba(${color},1)`;  
    }
    const color = colorStr
        .match(/[A-z0-9]{2}/g)
        .map(ele => parseInt(`0x${ele}`));  
    if (len === 6) {
        return `rgba(${color.join(",")},1)`;  
    }  
    if (len === 8) {    
        const opacity = (color.pop() / 255).toFixed(2);
        return `rgba(${color.slice(0, 3).join(",")}, ${opacity})`;  
    }
}複製代碼

RGBA 轉換成十六進制

安卓顯示顏色的十六進制是 ARGB格式,所以一開始我誤覺得網頁裏面顯示的十六進制也是 ARGB,實際是 RGBA也就是 hex的值

/** * description: 把rgba顏色轉化成十六進制顏色 * param {type} str爲rgba值, 例如rgba(255, 255, 255, 1); * return: 十六進制值 例如: #ffffffff */
function changeRgbaToHex(str) {  
    const colorArr = str.match(/(0\.)?\d+/g);
    const color = colorArr.map((ele, index, array) => {    
        if (index === array.length - 1) { 
            // 透明度 
            let opacity = (ele * 100 * 255) / 100;
            return Math.round(opacity)
                    .toString(16)
                    .padEnd(2, "0");    
        }
        return Number.parseFloat(ele)      
                .toString(16)      
                .padStart(2, "0");  
    });
    return `#${color.join("")}`;
}複製代碼

RGBA 轉換成 HSLA

轉換公式(來自維基百科, 最下面有連接, 點擊圖片能夠放大)


按照轉換公式實現代碼

/** * description: 把rgba顏色轉化成hsla顏色 * param {type} str爲rgba值, 例如rgba(15, 244, 235, 0.5); * return: hsla值 例如: hsla(178, 91%, 51%, 0.5) */
function changeRgbaToHSLA(str) {  
    const colorArr = str.match(/(0\.)?\d+/g);  
    const opacity = colorArr.pop();  
    const r = colorArr[0] / 255;  
    const g = colorArr[1] / 255;  
    const b = colorArr[2] / 255;  
    const max = Math.max(r, g, b);  
    const min = Math.min(r, g, b);  
    const num = max - min;  
    let h = 0;  
    let s = 0;  
    let l = 0.5 * (max + min);  
    if (max !== min) {    
        s = l <= 0.5 ? num / (2 * l) : num / (2 - 2 * l);    
        switch (max) {      
            case b:        
            h = ((r - g) / num) * 60 + 240;        
            break;      
            case g:        
            h = ((b - r) / num) * 60 + 120;
            break;      
            case r:        
            h = g >= b ? ((g - b) / num) * 60 : ((g - b) / num) * 60 + 360;
            break;      
            default:        
            break;    
         }  
    }  
    h = Math.round(h);  
    s = Math.round(s * 100);  
    l = Math.round(l * 100);  
    return `hsl(${h}, ${s}%, ${l}%, ${opacity})`;
}複製代碼

 HSL 轉換成 RGB

Hue, Saturation, Lightness 分別表明色相(0~360°)、飽和(0~100%)、亮度(0~100%)

轉換公式(來自維基百科, 最下面有連接, 點擊圖片能夠放大)


在公式中剛開始沒看懂tC是什麼,因此註明一下,tC就是tR,tG,tB三個變量按tC的規則分別進行運算最終獲得R、G、B的值

按照轉換公式實現代碼

/** * description: 把hsl顏色轉化成rgb顏色 * param {type} str爲hsl值, 例如hsl(178, 40%, 50%); * return: rgb值 例如: rgb(77, 179, 175) */
function changeHSLToRGB(str) {  
    const colorArr = str.match(/\d+/g);  
    let [h, s, l] = colorArr;  
    h = h / 360;  
    s = s / 100;  
    l = l / 100;  
    if (s === 0) {    
        l = Math.round(l * 255);    
        return `rgb(${l}, ${l}, ${l})`;
    }  
    const getRGB = num => {    
        let q = l >= 0.5 ? l + s - l * s : l * (1 + s); // 注意是數字1加上s,不是字母l
        let p = 2 * l - q;    
        if (num < 0) {      
            num += 1;    
        }    
        if (num > 1) {     
            num -= 1;    
        }    
        switch (true) {      
            case num > 2 / 3:        
            num = p;
            break;
            case num >= 1 / 2:
            num = p + (q - p) * 6 * (2 / 3 - num);
            break;
            case num >= 1 / 6:
            num = q;        
            break;      
            default:        
            num = p + (q - p) * 6 * num;        
            break;    
        }    
        return Math.round(num * 255);  
    };  
    let tR = getRGB(h + 1 / 3);  
    let tG = getRGB(h);  
    let tB = getRGB(h - 1 / 3);  
    return `rgb(${tR}, ${tG}, ${tB})`;
}複製代碼

總結一下

雖然可以進行顏色轉換,可是除了第一個代碼以外其餘的我都沒有判斷傳入的值是否正確,這是一個待完善的地方。不過總算了解了如何轉換,以後用到顏色轉換就可以開心的複製粘貼了。

參考教程

我的博客文章地址

【Tony's blog】javascript

相關文章
相關標籤/搜索