如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
一个完全不同的方法转换十六进制颜色代码到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'));
其他回答
我为RGB和十六进制颜色做了一个小的Javascript颜色类,这个类还包括RGB和十六进制验证函数。我将代码作为一个片段添加到这个答案中。
var colorClass = function() { this.validateRgb = function(color) { return typeof color === 'object' && color.length === 3 && Math.min.apply(null, color) >= 0 && Math.max.apply(null, color) <= 255; }; this.validateHex = function(color) { return color.match(/^\#?(([0-9a-f]{3}){1,2})$/i); }; this.hexToRgb = function(color) { var hex = color.replace(/^\#/, ''); var length = hex.length; return [ parseInt(length === 6 ? hex['0'] + hex['1'] : hex['0'] + hex['0'], 16), parseInt(length === 6 ? hex['2'] + hex['3'] : hex['1'] + hex['1'], 16), parseInt(length === 6 ? hex['4'] + hex['5'] : hex['2'] + hex['2'], 16) ]; }; this.rgbToHex = function(color) { return '#' + ('0' + parseInt(color['0'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['1'], 10).toString(16)).slice(-2) + ('0' + parseInt(color['2'], 10).toString(16)).slice(-2); }; }; var colors = new colorClass(); console.log(colors.hexToRgb('#FFFFFF'));// [255, 255, 255] console.log(colors.rgbToHex([255, 255, 255]));// #FFFFFF
哇。这些答案都不能处理分数的边缘情况,等等。当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');
}
}
ECMAScript 6版本的Tim Down的答案
将RGB转换为十六进制
const rgbToHex = (r, g, b) => '#' + [r, g, b]。映射(x => { const十六进制= x.toString(16) 返回十六进制。长度=== 1 ?'0' + hex: hex }) . join () console.log(rgbToHex(0,51,255));/ / # 0033 ff的
将十六进制转换为RGB
返回一个数组[r, g, b]。工作也与速记十六进制三胞胎,如“#03F”。
const hexToRgb = hex => hex.replace (/ ^ # ? (\ d] [a - f) (\ d] [a - f) (\ d] [a - f) $ /我 ,(m, r, g, b) => '#' + r + r + g + g + b + b) .substring (1) .match (/ {2} / g)。 .map(x => parseInt(x, 16)) console.log(hexToRgb("#0033ff")) // [0,51,255] console.log(hexToRgb("#03f")) // [0,51,255]
附加:RGB到十六进制使用padStart()方法
const rgbToHex = (r, g, b) => '#' + [r, g, b] .map(x => x. tostring(16)。padStart (2, ' 0 ')) . join () console.log(rgbToHex(0,51,255));/ / # 0033 ff的
注意,这个答案使用了最新的ECMAScript特性,旧的浏览器不支持这些特性。如果希望此代码在所有环境中都能工作,则应该使用Babel来编译代码。
基于@ michazperzhaakowski的回答(EcmaScipt 6)和他基于Tim Down的回答的回答
我写了一个转换hexToRGB函数的修改版本,增加了安全检查r/g/b颜色组件是否在0-255之间,而且函数可以接受数字r/g/b参数或字符串r/g/b参数,如下所示:
function rgbToHex(r, g, b) {
r = Math.abs(r);
g = Math.abs(g);
b = Math.abs(b);
if ( r < 0 ) r = 0;
if ( g < 0 ) g = 0;
if ( b < 0 ) b = 0;
if ( r > 255 ) r = 255;
if ( g > 255 ) g = 255;
if ( b > 255 ) b = 255;
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex
}).join('');
}
为了安全地使用这个函数——你应该检查传递的字符串是否是真正的rbg字符串颜色——例如,一个非常简单的检查可以是:
if( rgbStr.substring(0,3) === 'rgb' ) {
let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);
.....
}
这可以用于从计算样式属性中获取颜色:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
裁判:https://github.com/k-gun/so/blob/master/so_util.js