在 JavaScript 中将整数转换为十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4745317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting integers to hex string in JavaScript
提问by Toby Wilson
How do I convert integer byte values of red, green and blue to a hex string, which can then be assigned to a context for rendering onto a HTML5 canvas?
如何将红色、绿色和蓝色的整数字节值转换为十六进制字符串,然后可以将其分配给上下文以渲染到 HTML5 画布上?
For example, convert cyan,
例如,转换青色,
var r = 0;
var g = 255;
var b = 255;
To a hex string for assigning to a context fill colour.
分配给上下文填充颜色的十六进制字符串。
this.context.fillStyle = '#00FFFF';
Or is there a better way to do this altogether?
或者有没有更好的方法来完全做到这一点?
采纳答案by duncan
Just use the RGB values, like:
只需使用 RGB 值,例如:
this.context.fillStyle = "rgb(0,255,255)";
回答by nemisj
To convert a number to hex, you can use the built-in toString(16) function. Simple code:
要将数字转换为十六进制,您可以使用内置的 toString(16) 函数。简单代码:
function convert(integer) {
var str = Number(integer).toString(16);
return str.length == 1 ? "0" + str : str;
};
function to_rgb(r, g, b) { return "#" + convert(r) + convert(g) + convert(b); }
var color = to_rgb(r, g, b);
回答by Zango
I think, the simplest way is:
我认为,最简单的方法是:
var g = 255; g.toString(16); //gives "ff"
Use the feature that gives language.
使用提供语言的功能。
回答by kamoroso94
To convert your individual RGB values into a hex color, you can use this function, although it makes more sense just to use "rgb("+r+","+g+","+b+")"
instead.
要将您的单个 RGB 值转换为十六进制颜色,您可以使用此函数,尽管使用它更有意义"rgb("+r+","+g+","+b+")"
。
function rgbToHex(r,g,b) {
return "#"+("00000"+(r<<16|g<<8|b).toString(16)).slice(-6);
}
回答by Felipe Ribeiro
function pad(number, length) {
var str = '' + number;
while (str.length < length) str = '0' + str;
return str;
}
function toRGBHex(r,g,b) {
return pad(r.toString(16),2) + pad(g.toString(16),2) + pad(b.toString(16),2);
}
回答by Sachin Shanbhag
You can write your own method for this conversion -
您可以为此转换编写自己的方法 -
// function to generate the hex code
function getHex(dec)
{
var hexArray = new Array( "0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", "A", "B",
"C", "D", "E", "F" );
var code1 = Math.floor(dec / 16);
var code2 = dec - code1 * 16;
var decToHex = hexArray[code2];
return (decToHex);
}
original source - http://programming.top54u.com/post/Javascript-Convert-Decimal-to-Hex.aspx
原始来源 - http://programming.top54u.com/post/Javascript-Convert-Decimal-to-Hex.aspx