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

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


当前回答

这个代码片段将十六进制转换为rgb, rgb转换为十六进制。

视图演示

function hexToRgb(str) { 
    if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { 
        var hex = str.substr(1);
        hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
        var rgb = parseInt(hex, 16);               
        return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
    } 

    return false; 
}

function rgbToHex(red, green, blue) {
    var out = '#';

    for (var i = 0; i < 3; ++i) {
        var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);

        if (isNaN(n) || n < 0 || n > 255) {
            return false;
        }

        out += (n < 16 ? '0' : '') + n.toString(16);
    }
    return out
}

其他回答

如果你需要比较两个颜色值(给定为RGB,名称颜色或十六进制值)或转换为hex使用HTML5 canvas对象。

var canvas = document.createElement("canvas");
var ctx = this.canvas.getContext('2d');

ctx.fillStyle = "rgb(pass,some,value)";
var temp =  ctx.fillStyle;
ctx.fillStyle = "someColor";

alert(ctx.fillStyle == temp);
function getRGB(color){
  if(color.length == 7){
    var r = parseInt(color.substr(1,2),16);
    var g = parseInt(color.substr(3,2),16);
    var b = parseInt(color.substr(5,2),16);    
    return 'rgb('+r+','+g+','+b+')' ;
  }    
  else
    console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
 a = 'Enter correct value'; 
}

a;

My example =) color: { toHex: function(num){ var str = num.toString(16); return (str.length<6?'#00'+str:'#'+str); }, toNum: function(hex){ return parseInt(hex.replace('#',''), 16); }, rgbToHex: function(color) { color = color.replace(/\s/g,""); var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i); if(aRGB) { color = ''; for (var i=1; i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1'); } else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3'); return '#'+color; }

哇。这些答案都不能处理分数的边缘情况,等等。当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');
    }
}
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

使用这些函数来实现没有任何问题的结果。:)