Sin*_*dar 498 javascript rgb hex colors
如何将RGB格式的颜色转换为Hex格式,反之亦然?
例如,转换'#0080C0'
为(0, 128, 192)
.
Tim*_*own 1143
以下将对RGB到十六进制转换进行操作并添加任何所需的零填充:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Run Code Online (Sandbox Code Playgroud)
转换另一种方式:
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
Run Code Online (Sandbox Code Playgroud)
最后,另一个版本rgbToHex()
,正如@ casablanca的回答中所讨论的那样,并在@cwolves的评论中提出:
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Run Code Online (Sandbox Code Playgroud)
这里的一个版本hexToRgb()
也解析速记的三角形三元组,如"#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 136
hexToRgb的替代版本:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
Run Code Online (Sandbox Code Playgroud)
编辑:3/28/2017这是另一种方法 这似乎更快
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
Run Code Online (Sandbox Code Playgroud)
编辑:8/11/2017经过更多测试后,上面的新方法并不快:(.虽然这是一种有趣的替代方式.
Mic*_*ski 49
const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
const hex = x.toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Run Code Online (Sandbox Code Playgroud)
返回一个数组[r, g, b]
.也适用于速记十六进制三联体等"#03F"
.
const hexToRgb = hex =>
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
,(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]
Run Code Online (Sandbox Code Playgroud)
padStart()
方法const rgbToHex = (r, g, b) => '#' + [r, g, b]
.map(x => x.toString(16).padStart(2, '0')).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Run Code Online (Sandbox Code Playgroud)
请注意,此答案使用最新的ECMAScript功能,旧版浏览器不支持这些功能.如果您希望此代码适用于所有环境,则应使用Babel编译代码.
Fel*_*peC 43
这是我的版本:
function rgb2hex(red, green, blue) {
var rgb = blue | (green << 8) | (red << 16);
return '#' + (0x1000000 + rgb).toString(16).slice(1)
}
function hex2rgb(hex) {
// long version
r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (r) {
return r.slice(1,4).map(function(x) { return parseInt(x, 16); });
}
// short version
r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
if (r) {
return r.slice(1,4).map(function(x) { return 0x11 * parseInt(x, 16); });
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
cas*_*nca 26
我假设你的意思是HTML风格的十六进制表示法,即#rrggbb
.您的代码几乎是正确的,除非您已将订单撤消.它应该是:
var decColor = red * 65536 + green * 256 + blue;
Run Code Online (Sandbox Code Playgroud)
此外,使用位移可能会使它更容易阅读:
var decColor = (red << 16) + (green << 8) + blue;
Run Code Online (Sandbox Code Playgroud)
fal*_*lko 21
此代码接受#fff和#ffffff变体和不透明度.
function hex2rgb(hex, opacity) {
var h=hex.replace('#', '');
h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));
for(var i=0; i<h.length; i++)
h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);
if (typeof opacity != 'undefined') h.push(opacity);
return 'rgba('+h.join(',')+')';
}
Run Code Online (Sandbox Code Playgroud)
rez*_*ner 18
function hex2rgb(hex) {
return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 17
尝试(奖金)
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``
Run Code Online (Sandbox Code Playgroud)
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``
Run Code Online (Sandbox Code Playgroud)
Sha*_*son 16
令人惊讶的是这个答案还没有出现。
\nconst toRGB = (color) => {\n const { style } = new Option();\n style.color = color;\n return style.color;\n}\n// handles any color the browser supports and converts it.\nconsole.log(toRGB("#333")) // rgb(51, 51, 51);\nconsole.log(toRGB("hsl(30, 30%, 30%)"))
Run Code Online (Sandbox Code Playgroud)\r\n小智 12
十六进制转RGB
const hex2rgb = (hex) => {
const r = parseInt(hex.slice(1, 3), 16)
const g = parseInt(hex.slice(3, 5), 16)
const b = parseInt(hex.slice(5, 7), 16)
// return {r, g, b} // return an object
return [ r, g, b ]
}
console.log(hex2rgb("#0080C0"))
Run Code Online (Sandbox Code Playgroud)
RGB 到十六进制
const rgb2hex = (r, g, b) => {
var rgb = (r << 16) | (g << 8) | b
// return '#' + rgb.toString(16) // #80c0
// return '#' + (0x1000000 + rgb).toString(16).slice(1) // #0080c0
// or use [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)
return '#' + rgb.toString(16).padStart(6, 0)
}
console.log(rgb2hex(0, 128, 192))
Run Code Online (Sandbox Code Playgroud)
另外,如果有人需要在线工具,我已经构建了Hex 到 RGB,反之亦然。
K-G*_*Gun 11
这可用于从计算样式属性中获取颜色:
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
Run Code Online (Sandbox Code Playgroud)
参考:https://github.com/k-gun/so/blob/master/so_util.js
单线功能HEX到RGBA
支持短形式#fff
和长#ffffff
形式.
支持alpha通道(不透明度).
不管是否指定了哈希,都适用于这两种情况.
function hexToRGBA(hex, opacity) {
return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}
Run Code Online (Sandbox Code Playgroud)
例子:
hexToRGBA('#fff') -> rgba(255,255,255,1)
hexToRGBA('#ffffff') -> rgba(255,255,255,1)
hexToRGBA('#fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('ffffff', .2) -> rgba(255,255,255,0.2)
Run Code Online (Sandbox Code Playgroud)
(2017) SIMPLE ES6 可组合箭头函数
我忍不住为那些可能正在使用 ES6 编写一些现代功能/组合 js 的人分享这个。这是我在颜色模块中使用的一些光滑的单线,它为数据可视化进行颜色插值。
请注意,这根本不处理 alpha 通道。
const arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;
const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).splice(1, 3)
.map(v => Number(v));
const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你喜欢这种风格/语法,我写了一个全彩色模块(现代色彩),你可以从 npm 中获取。我做到了,所以我可以使用 prop getter 进行转换并解析几乎任何东西(Color.parse(anything))。如果你像我一样处理颜色,值得一看。
你可以追求这样的东西吗?
function RGB2HTML(red, green, blue)
{
return '#' + red.toString(16) +
green.toString(16) +
blue.toString(16);
}
alert(RGB2HTML(150, 135, 200));
Run Code Online (Sandbox Code Playgroud)
显示#9687c8
按位解决方案通常很奇怪。但是在这种情况下,我认为这更优雅
function hexToRGB(hexColor){
return {
red: (hexColor >> 16) & 0xFF,
green: (hexColor >> 8) & 0xFF,
blue: hexColor & 0xFF,
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
const {red, green, blue } = hexToRGB(0xFF00FF)
console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255
Run Code Online (Sandbox Code Playgroud)
//忽略hsl表示法,颜色值通常表示为名称,rgb,rgba或hex-
//十六进制可以是3个值或6.
// Rgb可以是百分比也可以是整数值.
//至少可以考虑所有这些格式.
String.prototype.padZero= function(len, c){
var s= this, c= c || "0", len= len || 2;
while(s.length < len) s= c + s;
return s;
}
var colors={
colornames:{
aqua: '#00ffff', black: '#000000', blue: '#0000ff', fuchsia: '#ff00ff',
gray: '#808080', green: '#008000', lime: '#00ff00', maroon: '#800000',
navy: '#000080', olive: '#808000', purple: '#800080', red: '#ff0000',
silver: '#c0c0c0', teal: '#008080', white: '#ffffff', yellow: '#ffff00'
},
toRgb: function(c){
c= '0x'+colors.toHex(c).substring(1);
c= [(c>> 16)&255, (c>> 8)&255, c&255];
return 'rgb('+c.join(',')+')';
},
toHex: function(c){
var tem, i= 0, c= c? c.toString().toLowerCase(): '';
if(/^#[a-f0-9]{3,6}$/.test(c)){
if(c.length< 7){
var A= c.split('');
c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3];
}
return c;
}
if(/^[a-z]+$/.test(c)){
return colors.colornames[c] || '';
}
c= c.match(/\d+(\.\d+)?%?/g) || [];
if(c.length<3) return '';
c= c.slice(0, 3);
while(i< 3){
tem= c[i];
if(tem.indexOf('%')!= -1){
tem= Math.round(parseFloat(tem)*2.55);
}
else tem= parseInt(tem);
if(tem< 0 || tem> 255) c.length= 0;
else c[i++]= tem.toString(16).padZero(2);
}
if(c.length== 3) return '#'+c.join('').toLowerCase();
return '';
}
}
//var c='#dc149c';
//var c='rgb(100%,25%,0)';
//
var c= 'red';
alert(colors.toRgb(c)+'\n'+colors.toHex(c));
Run Code Online (Sandbox Code Playgroud)
@Tim,添加到你的答案(它有点尴尬,将其纳入评论).
如上所述,我发现rgbToHex函数返回一个字符串,该字符串包含点之后的元素,并且它要求r,g,b值落在0-255范围内.
我相信这对大多数人来说似乎是显而易见的,但我花了两个小时才弄明白,到那时原来的方法已经膨胀到7行,然后才发现我的问题出现在其他地方.因此,为了节省其他时间和麻烦,这是我稍微修改过的代码,它检查先决条件并修剪字符串的无关位.
function rgbToHex(r, g, b) {
if(r < 0 || r > 255) alert("r is out of bounds; "+r);
if(g < 0 || g > 255) alert("g is out of bounds; "+g);
if(b < 0 || b > 255) alert("b is out of bounds; "+b);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用rgb-hex和hex-rgb,因为它经过了实战测试,并且具有其他解决方案中不可用的多个选项。
我最近正在构建一个颜色选择器,这两个包派上了用场。
import rgbHex from 'rgb-hex';
rgbHex(65, 131, 196);
//=> '4183c4'
rgbHex('rgb(40, 42, 54)');
//=> '282a36'
rgbHex(65, 131, 196, 0.2);
//=> '4183c433'
rgbHex(40, 42, 54, '75%');
//=> '282a36bf'
rgbHex('rgba(40, 42, 54, 75%)');
//=> '282a36bf'
Run Code Online (Sandbox Code Playgroud)
import hexRgb from 'hex-rgb';
hexRgb('4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#fff');
//=> {red: 255, green: 255, blue: 255, alpha: 1}
hexRgb('#22222299');
//=> {red: 34, green: 34, blue: 34, alpha: 0.6}
hexRgb('#0006');
//=> {red: 0, green: 0, blue: 0, alpha: 0.4}
hexRgb('#cd2222cc');
//=> {red: 205, green: 34, blue: 34, alpha: 0.8}
hexRgb('#cd2222cc', {format: 'array'});
//=> [205, 34, 34, 0.8]
hexRgb('#cd2222cc', {format: 'css'});
//=> 'rgb(205 34 34 / 80%)'
hexRgb('#000', {format: 'css'});
//=> 'rgb(0 0 0)'
hexRgb('#22222299', {alpha: 1});
//=> {red: 34, green: 34, blue: 34, alpha: 1}
hexRgb('#fff', {alpha: 0.5});
//=> {red: 255, green: 255, blue: 255, alpha: 0.5}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
417496 次 |
最近记录: |