Convert rgb strings to hex in Javascript

前端 未结 8 1149
借酒劲吻你
借酒劲吻你 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 01:55

    I would at first cut away the CSS parts:

    var a = "rgb(255,255,255)".split("(")[1].split(")")[0];
    

    Then split it into separate numbers:

    a = a.split(",");
    

    Convert the single numbers to hex

    var b = a.map(function(x){             //For each array element
        x = parseInt(x).toString(16);      //Convert to a base16 string
        return (x.length==1) ? "0"+x : x;  //Add zero if we get only one character
    })
    

    And glue it back together:

    b = "0x"+b.join("");
    

提交回复
热议问题