javascript - 十进制值到 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 或更少时,停止更改我正在编辑的组件的颜色。
当r
和b
为 0 且g
大于 16 时也会发生同样的情况。在这种情况下,g 在小于 16 时将颜色更改为红色,而当它大于 16 时则不显示颜色。这是一个 gif 来显示我的问题:
color-editing-problem-gif
或
替代
解决方案
...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")}
推荐阅读
- java - Lombok的@NonNull的使用说明
- html - 在 Bootstrap 4 中使用 form-inline 时创建填充
- c++ - sizeof 运算符如何计算函数返回类型的大小?
- asp.net-mvc - 如何在 .net 核心中创建自定义会话包装类并访问控制器外部
- python - 如何计算召回率、精度和 f-measure?
- mp4 - 是否可以在 mp4 文件的一个轨道中存储多个视频段落,每个段落都有自己的参数?
- c++ - x86 asm 在 __declspec(naked) 函数中访问和编辑 stdcall 函数参数
- r - 避免在 .SD 越界索引期间创建 NA
- javascript - 在画布中裁剪图像
- java - 错误:没有找到 void org.webrtc.PeerConnectionFactory.initializeFieldTrials 的实现