首页 > 解决方案 > 十进制值到 rgb 并返回到十进制

问题描述

我有十进制形式的颜色,需要将其转换为 rgb 并返回 de,所以我用它来这样做:

var currentcolor = 0xffd100;

const rgb_format = (c) => {
  var newrgb = {r: (c & 0xff0000) >> 16,
                g: (c & 0x00ff00) >> 8,
                b: (c & 0x0000ff)}

  return newrgb;
};

var rgb = rgb_format(currentcolor);

const decimal_format = (newrgb) => {
  let decimal = (newrgb.r << 16) + (newrgb.g << 8) + (newrgb.b);

  console.log(decimal);

  return decimal;
};

color.color = decimal_format(rgb);

问题是,我有一个 rgb 编辑器,每个值(r,g,b)都有滑块。它们可以正常工作,但是当r其他滑块(g,b)中的值为 16 或更少时,停止更改我正在编辑的组件的颜色。

rb为 0 且g大于 16 时也会发生同样的情况。在这种情况下,g 在小于 16 时将颜色更改为红色,而当它大于 16 时则不显示颜色。这是一个 gif 来显示我的问题: color-editing-problem-gif替代

标签: javascriptrgb

解决方案


...I am also displaying the color like this: style="background: #{currentcolor.toString(16)};

That won't work correctly. Consider the color 1092 decimal (0x000444). If currentcolor has that value, currentcolor.toString(16) results in 444. #444 is not the same as #000444 in CSS, #444 is the color #444444. Similarly, the color 65535 (0x00FFFF) will result in #ffff, which is an invalid CSS color (they must be three or six digits, not four).

To output the color correctly, you need to pad the start of the string:

style="background: #{currentcolor.toString(16).padStart(6, "0")}

推荐阅读