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?
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?
The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. The toString() method is used with a number num as shown in the above syntax using the '. ' operator.
Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.
JavaScript supports the use of hexadecimal notation in place of any integer, but not decimals. As an example, the number 2514 in hex is 0x9D2, but there is no language-supported way of representing 25.14 as a hex number.
Hex string is the binary value of the string in hexadecimal notation. Since the binary value differs depending on the character encoding, the conversion result to a hex string also differs.
To convert a number to hex, you can use the built-in toString(16) function. Simple code:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With