【问题标题】:JavaScript convert RGB integers to Hexadecimal [duplicate]JavaScript将RGB整数转换为十六进制[重复]
【发布时间】:2016-03-09 00:38:08
【问题描述】:

我正在使用 Vivagraph JS 库来渲染一些图形。

我想像这样改变节点的颜色

nodeUI.color = 0xFFA500FF;

^ 这是一个随机的例子。不是下面RGB对应的十六进制值

我从服务器 RGB 值作为这样的数组获取

rgb = [229,64,51]

如何将 RGB 转换为上面提到的十六进制类型值?

谢谢

【问题讨论】:

  • 0xFFA500FF 这个值是什么,你如何从rgb(229,64,51) 得到它,因为它的hex 值是#E54033
  • 如果this
  • @Roope——如果你愿意,你可以把它标记为骗子。
  • @RobG 当然,问题是如果你不明确指出人们似乎永远不会学习。
  • @Roope——你可以两者兼得。 ;-)

标签: javascript arrays hex rgb vivagraphjs


【解决方案1】:

根据此处代码中的 cmets:https://github.com/anvaka/VivaGraphJS/blob/master/demos/other/webglCustomNode.html

值 0xFFA500FF 是一个 32 位值,包含一个 Alpha 通道,因此忽略 Alpha 通道它相当于 rgb(255,165,0)。

下面是一些将 32 位十六进制转换为 24 位 rgb 并返回的函数,cmets 应该足以解释它们是如何工作的。

/*  @param {number} v - value to convert to RGB values
**  @returns {Array}  - three values for equivalent RGB triplet
**                      alpha channel is ingored
**
**  e.g. from32toRGB(0xaec7e8) // 255,165,0
*/
function from32toRGB(v) {
  var rgb = ('0000000' + v.toString(16))  // Convert to hex string with leading zeros
             .slice(-8)     // Get last 8 characters
             .match(/../g)  // Split into array of character pairs
             .splice(0,3)   // Get first three pairs only
             .map(function(v) {return parseInt(v,16)}); // Convert each value to decimal
  return rgb;
}

/*  @param {Array} rgbArr - array of RGB values
**  @returns {string}     - Hex value for equivalent 32 bit color
**                          Alpha is always 1 (FF)
**
**  e.g. fromRGBto32([255,165,0]) // aec7e8FF
**
**  Each value is converted to a 2 digit hex string and concatenated
**  to the previous value, with ff (alpha) appended to the end
*/
function fromRGBto32(rgbArr) {
  return rgbArr.reduce(function(s, v) {
    return s + ('0' + v.toString(16)).slice(-2);
  },'') + 'ff'
}

//  Tests for from32toRGB
  [0xFFA500FF, 0xaec7e8ff,0,0xffffffff].forEach(function(v) {
    document.write(v.toString(16) + ' : ' + from32toRGB(v) + '<br>')
  });

document.write('<br>');

// Tests for fromRGBto32
  [[255,165,0],[174,199,232], [0,0,0], [255,255,255]].forEach(function(rgbArr) {
    document.write(rgbArr + ' : ' + fromRGBto32(rgbArr) + '<br>');
  });

注意在作业中:

odeUI.color = 0xFFA500FF

十六进制值 0xFFA500FF 立即转换为十进制 11454440。要将 fromRGBto32 的结果转换为可以分配给 odeUI.color 的数字,请使用 parseInt:

parseInt(fromRGBto32([229,64,51]), 16);

或者如果你想硬编码,只需在前面添加“0x”即可。

如果你有一个像 'rgb(229,64,51)' 这样的字符串,你可以通过获取数字、转换为十六进制字符串并连接来将其转换为十六进制值:

var s = 'rgb = [229,64,51]';
var hex = s.match(/\d+/g);

if (hex) {
  hex = hex.reduce(function(acc, value) {
    return acc + ('0' + (+value).toString(16)).slice(-2);
  }, '#')
}

document.write(hex + '<br>');

// Append FF to make 32 bit and convert to decimal
// equivalent to 0xe54033ff
document.write(parseInt(hex.slice(-6) + 'ff', 16)); // 0xe54033ff -> 3846190079

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 2012-11-01
    • 2020-01-04
    • 2020-11-14
    • 2010-10-16
    相关资源
    最近更新 更多