如何将颜色在RGB格式转换为十六进制格式,反之亦然?

例如,将'#0080C0'转换为(0,128,192)。


当前回答

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

其他回答

如果这有助于任何人,我的API有这些转换的函数。

<script src="http://api.xlww.net/xQuery/xQuery.js"></script>
<script>
  x.init();
  var rgb=new x.rgb(37,255,83);
  alert(rgb.hex);
  var hex=new x.hex("#ffa500");
  alert("("+hex.rgb[0]+","+hex.rgb[1]+","+hex.rgb[2]+")");
</script>

试(奖金)

let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``

让hex2rgb = c = > ' rgb ($ {c.match (w / \ \ w / g) . map (x = > + 0 x $ {x})})”; 让rgb2hex = c = > ' # ' + c.match (\ d + / g) . map (x = > (+ x) .toString (16) .padStart (2,0)) . join '; / /测试 console.log('#0080C0—>',hex2rgb('#0080C0')); console.log(“rgb(0, 128, 192)——>”,rgb2hex(的rgb (0, 128, 192)));

我给洛达什做了这个。它将一个RGB字符串,如“30,209,19”转换为其对应的十六进制字符串“#1ed113”:

var rgb = '30,209,19';

var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
    var intColor = _.parseInt(rgbValue);

    if (_.isNaN(intColor)) {
        throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
    }

    // Ensure a value such as 2 is converted to "02".
    var hexColor = _.padLeft(intColor.toString(16), 2, '0');

    return hexAccumulator + hexColor;
}, '#');

哇。这些答案都不能处理分数的边缘情况,等等。当r, g, b为零时,位移版本也不起作用。

这是一个可以处理r g b是小数的版本。它对颜色之间的插值很有用,所以我也包括了这段代码。但它仍然不能处理r, g, b在0-255范围之外的情况

/**
 * Operates with colors.
 * @class Q.Colors
 */
 Q.Color = {
    /**
     * Get a color somewhere between startColor and endColor
     * @method toHex
     * @static
     * @param {String|Number} startColor 
     * @param {String|Number} endColor 
     * @param {String|Number} fraction 
     * @returns {String} a color as a hex string without '#' in front
     */
    toHex: function (r, g, b) {
        return [r, g, b].map(x => {
            const hex = Math.round(x).toString(16)
            return hex.length === 1 ? '0' + hex : hex
          }).join('');
    },
    /**
     * Get a color somewhere between startColor and endColor
     * @method between
     * @static
     * @param {String|Number} startColor 
     * @param {String|Number} endColor 
     * @param {String|Number} fraction 
     * @returns {String} a color as a hex string without '#' in front
     */
    between: function(startColor, endColor, fraction) {
        if (typeof startColor === 'string') {
            startColor = parseInt(startColor.replace('#', '0x'), 16);
        }
        if (typeof endColor === 'string') {
            endColor = parseInt(endColor.replace('#', '0x'), 16);
        }
        var startRed = (startColor >> 16) & 0xFF;
        var startGreen = (startColor >> 8) & 0xFF;
        var startBlue = startColor & 0xFF;
        var endRed = (endColor >> 16) & 0xFF;
        var endGreen = (endColor >> 8) & 0xFF;
        var endBlue = endColor & 0xFF;
        var newRed = startRed + fraction * (endRed - startRed);
        var newGreen = startGreen + fraction * (endGreen - startGreen);
        var newBlue = startBlue + fraction * (endBlue - startBlue);
        return Q.Color.toHex(newRed, newGreen, newBlue);
    },
    /**
     * Sets a new theme-color on the window
     * @method setWindowTheme
     * @static
     * @param {String} color in any CSS format, such as "#aabbcc"
     * @return {String} the previous color
     */
    setWindowTheme: function (color) {
        var meta = document.querySelector('meta[name="theme-color"]');
        var prevColor = null;
        if (meta) {
            prevColor = meta.getAttribute('content');
        }
        if (color) {
            if (!meta) {
                meta = document.createElement('meta');
                meta.setAttribute('name', 'theme-color');
            }
            meta.setAttribute('content', color);
        }
        return prevColor;
    },
    /**
     * Gets the current window theme color
     * @method getWindowTheme
     * @static
     * @param {String} color in any CSS format, such as "#aabbcc"
     * @return {String} the previous color
     */
    getWindowTheme: function () {
        var meta = document.querySelector('meta[name="theme-color"]');
        return meta.getAttribute('content');
    }
}

HTML converer :)

<!DOCTYPE html>
<html>
<body>

<p id="res"></p>

<script>
function hexToRgb(hex) {
  var res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return "(" + parseInt(res[1], 16) + "," + parseInt(res[2], 16) + "," + parseInt(res[3], 16) + ")";
};

document.getElementById("res").innerHTML = hexToRgb('#0080C0');
</script>

</body>
</html>