StoneHeart
StoneHeart

Reputation: 16610

Convert RGB to Hex color

Below is a function to convert rgb to hex color. But it is not totally correct. With (0, 255, 0) (#00ff00). it return ff00 and so it is not valid color. I need help to modify it to return correct hex value.

function rgbToHex(r, g, b) {
        var rgb = b | (g << 8) | (r << 16);
        return rgb.toString(16);
    }

Upvotes: 1

Views: 6383

Answers (8)

Bora Ke&#231;eci
Bora Ke&#231;eci

Reputation: 138

function rgb(r, g, b){

  let string = []
  string.push(r,g,b)
  string = string.map((e) => e < 16 && e >= 0 ? "0" + e.toString(16).toUpperCase() : e )
  string = string.map((e) => e >= 255 ? "FF" : e )
  string = string.map((e) => e < 0 ? "00" : e )
  string = string.map((e) => e > 0 && e < 255 ? e.toString(16).toUpperCase() : e )
  
return string.join("")
}

To protect the shape of it , i drew borders with maps. As you can see on the table toString(16) provides us single digit number. So, to prevent missing digit, i add zero in first .map function. Rest of it seems clear, if you get stuck please inform me .

Hexadecimal Table

Upvotes: 0

B T
B T

Reputation: 60975

How about using a library like the xolor library:

var color = xolor([45, 100, 200])
color.rgb // "rgb(45,100,200)"
color.hex // "2D64C8"
color.hsl // {h: 219, s:63.3, l:48.0}
color.hsv // {h: 218.7, s:0.7750, v:0.7843}
color.name // "royalblue"

Upvotes: 0

Vitim.us
Vitim.us

Reputation: 22198

Just another alternative

function rgbToHex(r, g, b) {
    function c(v) {
        var hex = v.toString(16);
        return hex.length === 1 ? "0" + hex : hex;
    }
    return "#" + c(r) + c(g) + c(b);
}

Upvotes: 0

Ben
Ben

Reputation: 494

Disclaimer: I'm the author of the pusher.color library mentioned below.

If you don't mind using a library, you may want to try a library like pusher.color or xcolor. I've noticed you've asked a few questions on Stackoverflow about color manipulation in Javascript, so this might save you some time overall to use a library to solve your problem. The pusher.color syntax for what you want would be:

var hexString = pusher.color('rgb', r, g, b).hex6();

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44426

How about this:

return $.sprintf("#%02x%02x%02x", r, g, b);

For this you need to use jQuery.

Upvotes: -2

Roman
Roman

Reputation: 6458

return ((b | g << 8 | r << 16) / 16777216).toString(16).substring(2);

or

return ((b | g << 8 | r << 16) / 0x1000000).toString(16).substring(2);

Upvotes: 1

Engineer
Engineer

Reputation: 48813

Try this:

return ("000000"+rgb.toString(16)).slice(-6);
//                                   ^----returns last 6 chars

Upvotes: 3

xiaowl
xiaowl

Reputation: 5217

How about this:

//...
return (0x1000000 | rgb).toString(16).substring(1);

Upvotes: 8

Related Questions