Convert rgb strings to hex in Javascript

前端 未结 8 1128
借酒劲吻你
借酒劲吻你 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:09

    The following is adapted from a Colour class I wrote and use but may be overkill for your needs since it handles percentages and negative numbers.

    Demo: http://jsfiddle.net/5ryxx/1/

    Code:

    function componentFromStr(numStr, percent) {
        var num = Math.max(0, parseInt(numStr, 10));
        return percent ?
            Math.floor(255 * Math.min(100, num) / 100) : Math.min(255, num);
    }
    
    function rgbToHex(rgb) {
        var rgbRegex = /^rgb\(\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*,\s*(-?\d+)(%?)\s*\)$/;
        var result, r, g, b, hex = "";
        if ( (result = rgbRegex.exec(rgb)) ) {
            r = componentFromStr(result[1], result[2]);
            g = componentFromStr(result[3], result[4]);
            b = componentFromStr(result[5], result[6]);
    
            hex = "0x" + (0x1000000 + (r << 16) + (g << 8) + b).toString(16).slice(1);
        }
        return hex;
    }
    

提交回复
热议问题