[顏色進位制轉換]js實現rgb和hex的相互轉換

梓川禰豆子發表於2020-12-14




將rgb顏色轉成hex

// 將rgb顏色轉成hex  輸入(24,12,255)
function colorRGB2Hex(r,g,b) {
    
    let hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
}

rgb色轉成hex : colorRGB2Hex(255,255,255);

返回hex值 如#cccccc

image-20201214121946426





將hex顏色轉成rgb

// 將hex顏色轉成rgb
function hexToRgba(hex, opacity) {
    let RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt( "0x" + hex.slice(5, 7)) + "," + opacity + ")";
    return {
        red: parseInt("0x" + hex.slice(1, 3)),
        green: parseInt("0x" + hex.slice(3, 5)),
        blue: parseInt("0x" + hex.slice(5, 7)),
        rgba: RGBA
    }
}

hex轉成rgba: hexToRgba("#cccccc", 1);

第一個引數為hex色值,第二個引數為透明度,返回物件

image-20201214121824134

相關文章