Convert rgb strings to hex in Javascript

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

提交回复
热议问题