如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
哇。这些答案都不能处理分数的边缘情况,等等。当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');
}
}
其他回答
一个完全不同的方法转换十六进制颜色代码到RGB没有正则表达式
它根据字符串长度处理#FFF和#FFFFFF格式。它从字符串的开头删除#,并将字符串的每个字符分割并将其转换为base10,并将其添加到其位置的相应索引中。
//Algorithm of hex to rgb conversion in ES5 function hex2rgbSimple(str){ str = str.replace('#', ''); return str.split('').reduce(function(result, char, index, array){ var j = parseInt(index * 3/array.length); var number = parseInt(char, 16); result[j] = (array.length == 3? number : result[j]) * 16 + number; return result; },[0,0,0]); } //Same code in ES6 hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]); //hex to RGBA conversion hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]); //hex to standard RGB conversion hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`; console.log(hex2rgb('#aebece')); console.log(hex2rgbSimple('#aebece')); console.log(hex2rgb('#aabbcc')); console.log(hex2rgb('#abc')); console.log(hex2rgba('#abc', 0.7)); console.log(hex2rgbStandard('#abc'));
我假设您指的是html风格的十六进制符号,即#rrggbb。你的代码几乎是正确的,只是顺序颠倒了。它应该是:
var decColor = red * 65536 + green * 256 + blue;
此外,使用位移位可能会让它更容易阅读:
var decColor = (red << 16) + (green << 8) + blue;
如果你需要比较两个颜色值(给定为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);
我发现了这个… http://jsfiddle.net/Mottie/xcqpF/1/light/
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
对于直接从jQuery转换,您可以尝试:
function rgbToHex(color) {
var bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
}
rgbToHex($('.col-tab-bar .col-tab span').css('color'))