如何将整数转换为javascript颜色? [英] How do I convert an integer to a javascript color?
问题描述
我有一个整数,需要将其转换为javascript中的颜色.我正在使用MVC模型,并试图在用于Web界面的软件中复制模型.我有数据库中整数格式的颜色.需要将其转换为javascript中的颜色.
I have an integer which I need to convert to a color in javascript. I am using an MVC model and am trying to replicate a model in a software for a web interface. I have the color in integer format from the database. It needs to be converted to a color in javascript.
例如:-12525360,-5952982之类的整数
For example: integers like -12525360, -5952982
我有这样的代码:
items[x].barStyle = "stroke: Black; fill = Red";
因此,我不需要给它填充红色,而是给它与整数值相对应的确切颜色.
So instead of giving the fill:Red, I need to give it the exact color corresponding to the integer value.
这是我用C#编写的代码.我需要在javascript中做同样的事情.这里resourcecolor =整数输入.
This is the code I have written in C#. I need the same thing in javascript. Here resourcecolor= the integer input.
var bytes = BitConverter.GetBytes(resourcecolor);
ti.color = Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]);
推荐答案
在javascript中,您将要与画布或css一起使用的ARGB颜色表示为字符串,例如"rgba(0-255,0-255,0-255,0-1)"
.
In javascript, you express a ARGB color that is to be used with canvas or css as a string like "rgba(0-255,0-255,0-255,0-1)"
.
您可以使用以下函数将整数转换为该字符串格式:
You can convert the integer to that string format with this function:
function toColor(num) {
num >>>= 0;
var b = num & 0xFF,
g = (num & 0xFF00) >>> 8,
r = (num & 0xFF0000) >>> 16,
a = ( (num & 0xFF000000) >>> 24 ) / 255 ;
return "rgba(" + [r, g, b, a].join(",") + ")";
}
toColor(-5952982)
//"rgba(165,42,42,1)"
toColor(-12525360)
//"rgba(64,224,208,1)"
演示: http://jsfiddle.net/Ectpk/
这篇关于如何将整数转换为javascript颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!