30

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?

8 Answers 8

38

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);
Sign up to request clarification or add additional context in comments.

Comments

17

Just use the RGB values, like:

this.context.fillStyle = "rgb(0,255,255)";

8 Comments

The best answers are always the simplest!
But thanks everyone else who replied, they were interesting answers and valuable to my knowledge & understanding. +1 each.
@ElRonnoco According to one person's post it works in NN7+, IE5+, Mozilla 1.0+. So yes, very cross-browser compatible. (The same cannot be said for rgba(...).)
Oi. This is not answering the question asked. The answer below, Number(integer).toString(16) is correct and should be accepted.
@DavidFischer answering the 2nd part of the question I think
|
14

I think, the simplest way is:

var g = 255;
g.toString(16); //gives "ff"

Use the feature that gives language.

3 Comments

This answer is missing the 0-padding necessary for hexadecimal color values.
'0x' + g.toString(16), add a prefix is pretty simple
You can use padStart for this: g.toString(16).padStart(2, '0')
4

Convert one integer to a hex byte like:

const g = 255;

gPadded = Number(g).toString(16).padStart(2, "0");

This gets nicer with an array:

const r = 0;
const g = 255;
const b = 255;
const color = [r, g, b];

this.context.fillStyle = "#" + color.map(i=>i.toString(16).padStart(2, "0")).join("");

Comments

1
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); 
}

Comments

1

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.

function rgbToHex(r,g,b) {
    return "#"+("00000"+(r<<16|g<<8|b).toString(16)).slice(-6);
}

2 Comments

~ fyi I have incorporated your edit to my answer, despite it having been rejected. stackoverflow.com/questions/17945972/… (no good way to send message here)
@MightyPork oh, alright, thanks for telling me. Yeah, there should be a way to inbox people on here. Oh well.
1

You can use .toString(16)

let decimalNumber = 255;
decimalNumber.toString(16)
// Expected output is "FF"

or if you want to convert binary radix

let decimalNumber = 24;
decimalNumber.toString(2)
// Expected output is "1010"

source MDN .toString(16)

Comments

0

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

5 Comments

This will only convert one nibble.
@El Ronnoco - Please check the link. We run a loop for calling this function when decimal number is greater than 15.
@Tomas - that depends on how you want to use it. I think I have given a link of already existing code which is open for your customization. Dont you think downvote is a bit harsh here?
The link seems to be broken.
link seems broken, I don't know why this should be downvoted?! It's a valid function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.