如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
你想要这样的东西吗?
function RGB2HTML(red, green, blue)
{
return '#' + red.toString(16) +
green.toString(16) +
blue.toString(16);
}
alert(RGB2HTML(150, 135, 200));
显示# 9687 c8
其他回答
我给洛达什做了这个。它将一个RGB字符串,如“30,209,19”转换为其对应的十六进制字符串“#1ed113”:
var rgb = '30,209,19';
var hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {
var intColor = _.parseInt(rgbValue);
if (_.isNaN(intColor)) {
throw new Error('The value ' + rgbValue + ' was not able to be converted to int');
}
// Ensure a value such as 2 is converted to "02".
var hexColor = _.padLeft(intColor.toString(16), 2, '0');
return hexAccumulator + hexColor;
}, '#');
这段代码接受#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(',')+')';
}
HTML converer :)
<!DOCTYPE html>
<html>
<body>
<p id="res"></p>
<script>
function hexToRgb(hex) {
var res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return "(" + parseInt(res[1], 16) + "," + parseInt(res[2], 16) + "," + parseInt(res[3], 16) + ")";
};
document.getElementById("res").innerHTML = hexToRgb('#0080C0');
</script>
</body>
</html>
试(奖金)
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``
让hex2rgb = c = > ' rgb ($ {c.match (w / \ \ w / g) . map (x = > + 0 x $ {x})})”; 让rgb2hex = c = > ' # ' + c.match (\ d + / g) . map (x = > (+ x) .toString (16) .padStart (2,0)) . join '; / /测试 console.log('#0080C0—>',hex2rgb('#0080C0')); console.log(“rgb(0, 128, 192)——>”,rgb2hex(的rgb (0, 128, 192)));
以下是我的看法:
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;
}