Convert rgb strings to hex in Javascript

前端 未结 8 1152
借酒劲吻你
借酒劲吻你 2021-02-07 01:21

I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always i

相关标签:
8条回答
  • 2021-02-07 02:13

    rgb2Hex = s => s.match(/[0-9]+/g).reduce((a, b) => a+(b|256).toString(16).slice(1), '0x')
    
    console.log(rgb2Hex('rgb(10, 11, 12)'), rgb2Hex('rgb(255, 256, 257)'))


    Not recommended for unreliable user input, but the string can also be evaluated as a function:

    rgb = (r, g, b) => '0x' + (1<<24|r<<16|g<<8|b).toString(16).slice(1)
    
    console.log(eval('rgb(10, 11, 12)'), eval('rgb(255)'))

    0 讨论(0)
  • 2021-02-07 02:17
    function parseColor(color) {
        var arr=[]; color.replace(/[\d+\.]+/g, function(v) { arr.push(parseFloat(v)); });
        return {
            hex: "#" + arr.slice(0, 3).map(toHex).join(""),
            opacity: arr.length == 4 ? arr[3] : 1
        };
    }
    function toHex(int) {
        var hex = int.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    

    parseColor("rgb(210, 10, 10)");  // {"hex":"#d20a0a","opacity":1}
    parseColor("rgba(210, 10, 10, 0.5)"); // {"hex":"#d20a0a","opacity":"0.5"}
    parseColor("rgb(210)");  // {"hex":"#d2","opacity":1}
    
    0 讨论(0)
提交回复
热议问题