RGB 到十六进制和十六进制到 RGB

发布于 2024-10-31 17:58:15 字数 102 浏览 5 评论 0 原文

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

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

How to convert colors in RGB format to hex format and vice versa?

For example, convert '#0080C0' to (0, 128, 192).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

兲鉂ぱ嘚淚 2024-11-07 17:58:15

注意rgbToHex 的两个版本都期望 rgb 为整数值,因此如果您有非整数值,则需要进行自己的舍入。

以下将对 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

另一种方式转换:

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";

最后,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

2012 年 12 月 3 日更新

这是 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";

Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.

The following will do to the RGB to hex conversion and add any required zero padding:

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

Converting the other way:

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";

Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:

function rgbToHex(r, g, b) {
  return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

Update 3 December 2012

Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#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";

无声情话 2024-11-07 17:58:15

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;
}

编辑:2017 年 3 月 28 日
这是另一种方法似乎更快

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];
}

编辑:8/11/2017
经过更多测试后,上面的新方法并不更快:(。尽管这是一种有趣的替代方法。

An alternative version of 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;
}

Edit: 3/28/2017
Here is another approach that seems to be even faster

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];
}

Edit: 8/11/2017
The new approach above after more testing is not faster :(. Though it is a fun alternate way.

北城孤痞 2024-11-07 17:58:15

Tim Down 的回答的 ECMAScript 6 版本

将 RGB 转换为十六进制

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'

将十六进制转换为 RGB

返回数组 [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]

奖励:使用 padStart() 方法将 RGB 转换为十六进制

const rgbToHex = (r, g, b) => '#' + [r, g, b]
  .map(x => x.toString(16).padStart(2, '0')).join('')

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

请注意,此答案使用最新的 ECMAScript 功能,旧版浏览器不支持这些功能。如果您希望此代码在所有环境中工作,您应该使用 Babel 来编译您的代码。

ECMAScript 6 version of Tim Down's answer

Converting RGB to hex

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'

Converting hex to RGB

Returns an array [r, g, b]. Works also with shorthand hex triplets such as "#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]

Bonus: RGB to hex using padStart() method

const rgbToHex = (r, g, b) => '#' + [r, g, b]
  .map(x => x.toString(16).padStart(2, '0')).join('')

console.log(rgbToHex(0, 51, 255)); // '#0033ff'

Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.

も让我眼熟你 2024-11-07 17:58:15

这是我的版本:

function rgbToHex(red, green, blue) {
  const rgb = (red << 16) | (green << 8) | (blue << 0);
  return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

function hexToRgb(hex) {
  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
  if (normal) return normal.slice(1).map(e => parseInt(e, 16));

  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
  if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));

  return null;
}

Here's my version:

function rgbToHex(red, green, blue) {
  const rgb = (red << 16) | (green << 8) | (blue << 0);
  return '#' + (0x1000000 + rgb).toString(16).slice(1);
}

function hexToRgb(hex) {
  const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
  if (normal) return normal.slice(1).map(e => parseInt(e, 16));

  const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
  if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));

  return null;
}
删除会话 2024-11-07 17:58:15
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
与往事干杯 2024-11-07 17:58:15

我假设您指的是 HTML 样式的十六进制表示法,即 #rrggbb。您的代码几乎是正确的,只是您的顺序颠倒了。它应该是:

var decColor = red * 65536 + green * 256 + blue;

另外,使用位移位可能会使它更容易阅读:

var decColor = (red << 16) + (green << 8) + blue;

I'm assuming you mean HTML-style hexadecimal notation, i.e. #rrggbb. Your code is almost correct, except you've got the order reversed. It should be:

var decColor = red * 65536 + green * 256 + blue;

Also, using bit-shifts might make it a bit easier to read:

var decColor = (red << 16) + (green << 8) + blue;
晚雾 2024-11-07 17:58:15

尝试(rgba 此处;奖金在这里

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``

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``;

// TEST
console.log('#0080C0          -->', hex2rgb('#0080C0'));
console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));

Try (rgba here; bonus here)

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``

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``;

// TEST
console.log('#0080C0          -->', hex2rgb('#0080C0'));
console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));

你曾走过我的故事 2024-11-07 17:58:15

单行功能十六进制到 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(isFinite(opacity) ? opacity : 1).join(',') + ')';
}

例子:

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)

hexToRGBA('#ffffff', 0)  ->  rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) ->  rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1)  ->  rgba(255,255,255,1)

One-line functional HEX to RGBA

Supports both short #fff and long #ffffff forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.

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(isFinite(opacity) ? opacity : 1).join(',') + ')';
}

examples:

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)

hexToRGBA('#ffffff', 0)  ->  rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) ->  rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1)  ->  rgba(255,255,255,1)
记忆で 2024-11-07 17:58:15

令人惊讶的是这个答案还没有出现。

  • 不使用任何库 #use-the-platform ✔️
  • 3 行,并处理任何颜色浏览器支持。
const toRGB = (color) => {
    const { style } = new Option();
    style.color = color;
    return style.color;
}
// handles any color the browser supports and converts it.
console.log(toRGB("#333")) // rgb(51, 51, 51);
console.log(toRGB("hsl(30, 30%, 30%)")) 

Surprised this answer hasn't come up.

  • Doesn't use any library #use-the-platform ✔️
  • 3 Lines, and handles any color browsers support.

const toRGB = (color) => {
    const { style } = new Option();
    style.color = color;
    return style.color;
}
// handles any color the browser supports and converts it.
console.log(toRGB("#333")) // rgb(51, 51, 51);
console.log(toRGB("hsl(30, 30%, 30%)")) 

极致的悲 2024-11-07 17:58:15

此代码接受 #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(',')+')';
}

This code accept #fff and #ffffff variants and opacity.

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(',')+')';
}
旧时模样 2024-11-07 17:58:15

按位解决方案通常很奇怪。但在这种情况下,我想这更优雅

Bitwise solution normally is weird. But in this case I guess that is more elegant ????

function hexToRGB(hexColor){
  return {
    red: (hexColor >> 16) & 0xFF,
    green: (hexColor >> 8) & 0xFF,  
    blue: hexColor & 0xFF,
  }
}

Usage:

const {red, green, blue } = hexToRGB(0xFF00FF)

console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255
枕花眠 2024-11-07 17:58:15

(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));

顺便说一句,如果你喜欢这种风格/语法,我编写了一个全彩色模块(现代颜色),你可以从 npm 获取。我这样做是为了可以使用 prop getter 进行转换并解析几乎任何内容(Color.parse(anything))。如果你像我一样经常处理颜色,那么值得一看。

(2017) SIMPLE ES6 composable arrow functions

I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.

Note that this does not handle the alpha channel at all.

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));

BTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do.

掩饰不了的爱 2024-11-07 17:58:15

这可用于从计算样式属性中获取颜色:

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

This could be used for getting colors from computed style propeties:

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

Ref: https://github.com/k-gun/so/blob/master/so_util.js

岁月染过的梦 2024-11-07 17:58:15

十六进制转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"))

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))

另外,如果有人需要在线工具,我已经构建了十六进制到RGB,反之亦然。

Hex to 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"))

RGB to Hex

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))

Also if someone need online tool, I have built Hex to RGB and vice versa.

做个少女永远怀春 2024-11-07 17:58:15

// 忽略 hsl 表示法,颜色值通常表示为名称、rgb、rgba 或十六进制-

// 十六进制可以是 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));

// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-

// Hex can be 3 values or 6.

// Rgb can be percentages as well as integer values.

// Best to account for all of these formats, at least.

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));
紫罗兰の梦幻 2024-11-07 17:58:15

你可以追求这样的东西吗?

function RGB2HTML(red, green, blue)
{
    return '#' + red.toString(16) +
           green.toString(16) +
           blue.toString(16);
}

alert(RGB2HTML(150, 135, 200));

显示#9687c8

May you be after something like this?

function RGB2HTML(red, green, blue)
{
    return '#' + red.toString(16) +
           green.toString(16) +
           blue.toString(16);
}

alert(RGB2HTML(150, 135, 200));

displays #9687c8

灼疼热情 2024-11-07 17:58:15

@蒂姆,添加到你的答案中(将其放入评论中有点尴尬)。

正如所写,我发现 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);
}

@ Tim, to add to your answer (its a little awkward fitting this into a comment).

As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.

I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.

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);
}
小女人ら 2024-11-07 17:58:15

如果您需要比较两个颜色值(以 RGB、名称颜色或十六进制值形式给出)或转换为十六进制,请使用 HTML5 画布对象。

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);

If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.

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);
戏舞 2024-11-07 17:58:15

2021 版本

您可以简单地使用 rgb-hex & hex-rgb 因为它经过了实战测试具有其他解决方案中不可用的多种选项。

我最近正在构建一个颜色选择器和这2个包派上了用场。

用法

rgb-hex 十六

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'

进制-rgb

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}

2021 version

You can simply use rgb-hex & hex-rgb as it is battle-tested & has multiple options that are not available in other solutions.

I was recently building a Color Picker & these 2 packages came in handy.

Usage

rgb-hex

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'

hex-rgb

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}
秋凉 2024-11-07 17:58:15

接受字符串的简写版本:

function rgbToHex(a){
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write(rgbToHex("rgb(255,255,255)"));

检查它是否还不是十六进制

function rgbToHex(a){
  if(~a.indexOf("#"))return a;
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));

Shorthand version that accepts a string:

function rgbToHex(a){
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write(rgbToHex("rgb(255,255,255)"));

To check if it's not already hexadecimal

function rgbToHex(a){
  if(~a.indexOf("#"))return a;
  a=a.replace(/[^\d,]/g,"").split(","); 
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}

document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));

薆情海 2024-11-07 17:58:15

2022:如果您经常操作颜色并且不介意使用包,

请使用 tinycolor2。它是一个用于在 JavaScript 中进行颜色操作和转换的快速库(大约 400kb)。

它接受各种颜色字符串格式。例如:

tinycolor("#000"); // Hex3
tinycolor("#f0f0f6"); // Hex6
tinycolor("#f0f0f688"); // Hex8
tinycolor("f0f0f6"); // Hex withouth the number sign '#'
tinycolor("rgb (255, 0, 0)"); // RGB
tinycolor("rgba (255, 0, 0, .5)"); // RGBA
tinycolor({ r: 255, g: 0, b: 0 }); // RGB object
tinycolor("hsl(0, 100%, 50%)"); // HSL
tinycolor("hsla(0, 100%, 50%, .5)"); // HSLA
tinycolor("red"); // Named

RGB 到 HEX

var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0

十六进制到 RGB

var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)

访问文档以获取更多演示。

2022: If you often manipulate colors and doesn't mind using a package,

Use tinycolor2. It's a fast library (Around 400kb) for color manipulation and conversion in JavaScript.

It accepts various color string format. Like:

tinycolor("#000"); // Hex3
tinycolor("#f0f0f6"); // Hex6
tinycolor("#f0f0f688"); // Hex8
tinycolor("f0f0f6"); // Hex withouth the number sign '#'
tinycolor("rgb (255, 0, 0)"); // RGB
tinycolor("rgba (255, 0, 0, .5)"); // RGBA
tinycolor({ r: 255, g: 0, b: 0 }); // RGB object
tinycolor("hsl(0, 100%, 50%)"); // HSL
tinycolor("hsla(0, 100%, 50%, .5)"); // HSLA
tinycolor("red"); // Named

RGB to HEX

var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0

HEX to RGB

var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)

Visit documentation for more demo.

金兰素衣 2024-11-07 17:58:15

基本上,十六进制到 rgb:

var hex = '0080C0'.match(/.{1,2}/g).map(e=>parseInt(e, 16));

如果你想要字符串

var rgb = `rgb(${hex.join(", ")})`

rgb 到十六进制:

var rgb_arr = [0, 128, 40];
var rgb = "#" + rgb_arr.map(e=>e.toString(16).padStart(2, 0)).join("")

basically, hex to rgb:

var hex = '0080C0'.match(/.{1,2}/g).map(e=>parseInt(e, 16));

if you want string

var rgb = `rgb(${hex.join(", ")})`

rgb to hex:

var rgb_arr = [0, 128, 40];
var rgb = "#" + rgb_arr.map(e=>e.toString(16).padStart(2, 0)).join("")
后知后觉 2024-11-07 17:58:15

我需要一个也接受无效值的函数,例如

rgb(-255, 255, 255)
rgb(510, 255, 255)

这是@cwolves 答案的衍生内容

function rgb(r, g, b) {
  this.c = this.c || function (n) {
    return Math.max(Math.min(n, 255), 0)
  };

  return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}

i needed a function that accepts invalid values too like

rgb(-255, 255, 255)
rgb(510, 255, 255)

this is a spin off of @cwolves answer

function rgb(r, g, b) {
  this.c = this.c || function (n) {
    return Math.max(Math.min(n, 255), 0)
  };

  return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}
鲜肉鲜肉永远不皱 2024-11-07 17:58:15
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}

使用这些函数可以毫无问题地获得结果。 :)

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}

Use these Function to achive the result without any issue. :)

╭ゆ眷念 2024-11-07 17:58:15

我建议使用经过良好测试和维护的库,而不是到处复制粘贴片段: Colors.js(适用于 Node.js 和浏览器)。它只有 7 KB(缩小后,压缩后更小)。

Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).

怪我闹别瞎闹 2024-11-07 17:58:15

我遇到了这个问题,因为我想解析任何颜色字符串值并能够指定不透明度,所以我编写了这个使用 画布 API

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

关于 context.fillStyle 的注意事项

如果解析该值导致失败,则必须将其忽略,并且该属性必须保留其先前的值。

这是一个可用于测试输入的堆栈片段演示:

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

var inputs = document.getElementsByTagName('input');

function setColor() {
  inputs[1].value = JSON.stringify(toRGBA(inputs[0].value));
  document.body.style.backgroundColor = inputs[0].value;
}

inputs[0].addEventListener('input', setColor);
setColor();
input {
  width: 200px;
  margin: 0.5rem;
}
<input value="cyan" />
<input readonly="readonly" />

I came across this problem since I wanted to parse any color string value and be able to specify an opacity, so I wrote this function that uses the canvas API.

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

Note about context.fillStyle:

If parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value.

Here's a Stack Snippet demo you can use to test inputs:

var toRGBA = function () {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  canvas.width = 1;
  canvas.height = 1;

  return function (color) {
    context.fillStyle = color;
    context.fillRect(0, 0, 1, 1);

    var data = context.getImageData(0, 0, 1, 1).data;

    return {
      r: data[0],
      g: data[1],
      b: data[2],
      a: data[3]
    };
  };
}();

var inputs = document.getElementsByTagName('input');

function setColor() {
  inputs[1].value = JSON.stringify(toRGBA(inputs[0].value));
  document.body.style.backgroundColor = inputs[0].value;
}

inputs[0].addEventListener('input', setColor);
setColor();
input {
  width: 200px;
  margin: 0.5rem;
}
<input value="cyan" />
<input readonly="readonly" />

一紙繁鸢 2024-11-07 17:58:15

将 RGB 转换为十六进制的简单答案。这里颜色通道的值被限制在 0 到 255 之间。

function RGBToHex(r = 0, g = 0, b = 0) {
    // clamp and convert to hex
    let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
    let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
    let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
    return "#" +
        (hr.length<2?"0":"") + hr +
        (hg.length<2?"0":"") + hg +
        (hb.length<2?"0":"") + hb;
}

A simple answer to convert RGB to hex. Here values of color channels are clamped between 0 and 255.

function RGBToHex(r = 0, g = 0, b = 0) {
    // clamp and convert to hex
    let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
    let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
    let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
    return "#" +
        (hr.length<2?"0":"") + hr +
        (hg.length<2?"0":"") + hg +
        (hb.length<2?"0":"") + hb;
}
眼泪淡了忧伤 2024-11-07 17:58:15

将 RGB 转换为十六进制

使用 padStart()

您可以使用 padStart() 使用此 oneliner:

const rgb = (r, g, b) => {
  return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}

PS旧版浏览器不支持它,在此处检查其兼容性。

不使用padStart()

如果你不想使用padStart(),你可以实现这个函数:

const rgb = (r, g, b) => {
  return `#${[r, g, b]
    .map((n) =>
      n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
    )
    .join("")}`;
};

参数验证

如果您不确定谁将使用您的函数,则必须使用参数验证,以确保值有效(0 到 255 之间),为此,请在每个 return< 之前添加这些条件/代码>:

if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;

那么上面的两个例子就变成了:

const rgb = (r, g, b) => {
  if (r > 255) r = 255; else if (r < 0) r = 0;
  if (g > 255) g = 255; else if (g < 0) g = 0;
  if (b > 255) b = 255; else if (b < 0) b = 0;
  return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
};

const rgb2 = (r, g, b) => {
  if (r > 255) r = 255; else if (r < 0) r = 0;
  if (g > 255) g = 255; else if (g < 0) g = 0;
  if (b > 255) b = 255; else if (b < 0) b = 0;
  return `#${[r, g, b]
    .map((n) =>
      n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
    )
    .join("")}`;
};


十六进制到 RGB

为此,我们将使用一些 RegEx

const hex = (h) => {
  return h
    .replace(
      /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
      (_, r, g, b) => "#" + r + r + g + g + b + b
    )
    .substring(1)
    .match(/.{2}/g)
    .map((x) => parseInt(x, 16));
};

RGB to Hex

Using padStart()

You can use this oneliner using padStart():

const rgb = (r, g, b) => {
  return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}

P.S. it isn't supported on legacy browsers, check its compatibility here.

Without padStart()

If you don't want to use padStart(), you can implement this function instead:

const rgb = (r, g, b) => {
  return `#${[r, g, b]
    .map((n) =>
      n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
    )
    .join("")}`;
};

Parameters validation

If you're not sure who is going to use your function, you have to use the parameters validations, that the values are valid (between 0 and 255), to do so, add these conditions before each return:

if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;

So the two above examples become:

const rgb = (r, g, b) => {
  if (r > 255) r = 255; else if (r < 0) r = 0;
  if (g > 255) g = 255; else if (g < 0) g = 0;
  if (b > 255) b = 255; else if (b < 0) b = 0;
  return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
};

const rgb2 = (r, g, b) => {
  if (r > 255) r = 255; else if (r < 0) r = 0;
  if (g > 255) g = 255; else if (g < 0) g = 0;
  if (b > 255) b = 255; else if (b < 0) b = 0;
  return `#${[r, g, b]
    .map((n) =>
      n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
    )
    .join("")}`;
};


Hex to RGB

For this, we are going to use some RegEx:

const hex = (h) => {
  return h
    .replace(
      /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
      (_, r, g, b) => "#" + r + r + g + g + b + b
    )
    .substring(1)
    .match(/.{2}/g)
    .map((x) => parseInt(x, 16));
};

白芷 2024-11-07 17:58:15

要直接从 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'))

For convert directly from jQuery you can try:

  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'))
善良天后 2024-11-07 17:58:15

虽然这个答案不太可能完全适合这个问题,但它可能非常有用。

  1. 创建任意随机元素

var toRgb = document.createElement('div');

  1. 将任何有效样式设置为要转换的颜色

toRg.style.color = "hsl(120, 60% , 70%)";

  1. 再次调用样式属性

> toRgb.style.color;

< "rgb(133, 225, 133)" 您的颜色已转换为 Rgb

适用于:Hsl、Hex

不适用于:命名颜色

While this answer is unlikely to fit the question perfectly it may be very useful none the less.

  1. Create any random element

var toRgb = document.createElement('div');

  1. Set any valid style to the color you want to convert

toRg.style.color = "hsl(120, 60%, 70%)";

  1. Call the style property again

> toRgb.style.color;

< "rgb(133, 225, 133)" Your color has been converted to Rgb

Works for: Hsl, Hex

Does not work for: Named colors

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文