3

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

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

nodeUI.color = 0xFFA500FF;

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

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

rgb = [229,64,51]

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

谢谢

4

1 回答 1

1

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

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

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

/*  @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

于 2015-12-04T06:47:50.913 回答