如何将RGB格式的颜色转换为十六进制格式,或将十六进制格式的颜色转换为RGB格式?
例如,将'#0080C0'
转换为 (0, 128, 192)
。
如何将RGB格式的颜色转换为十六进制格式,或将十六进制格式的颜色转换为RGB格式?
例如,将'#0080C0'
转换为 (0, 128, 192)
。
(2017) 简单的ES6可组合箭头函数
我无法抗拒与那些使用ES6编写现代函数式/组合JavaScript代码的人分享这个东西。以下是我在一个颜色模块中使用的一些简洁的一行代码,用于数据可视化的颜色插值。
请注意,这根本没有处理 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));
顺便提一下,如果你喜欢这种样式/语法,我写了一个完整的彩色模块(modern-color),可以从npm上获取。我制作它是为了能够使用属性获取器进行转换,并且可以解析几乎任何东西(Color.parse(anything))。如果你像我一样经常处理颜色,那么值得一看。
这可以用于获取计算样式属性中的颜色:
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
(该链接为一个JavaScript代码库)(r.length == 1 ? "0" + r : r)
,绿色和蓝色同理。 - user2373682十六进制转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转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))
如果有人需要在线工具,我建立了Hex to RGB和RGB到Hex的转换器。
惊讶的是这个答案还没有出现。
<div data-lang="js" data-hide="false" data-console="true" data-babel="false" class="snippet">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>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%)"))
toRGB('red'); // 返回 'red'
。下面的答案也只有3行代码,但是使用了Canvas元素的一个属性,而不是Option元素:https://stackoverflow.com/a/47355187/740639 - undefined你是否需要类似这样的内容?
function RGB2HTML(red, green, blue)
{
return '#' + red.toString(16) +
green.toString(16) +
blue.toString(16);
}
alert(RGB2HTML(150, 135, 200));
显示 #9687c8
// 忽略 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));
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);
}
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);
你可以直接使用rgb-hex和hex-rgb,因为它们经过实战检验,并且有多个选项可供选择,这是其他解决方案所没有的。
最近我在构建一个颜色选择器时,这2个软件包非常有用。
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'
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}
请使用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
var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0
var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)
访问文档以获取更多演示。