Reputation: 16610
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
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 .
Upvotes: 0
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
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
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
Reputation: 44426
How about this:
return $.sprintf("#%02x%02x%02x", r, g, b);
For this you need to use jQuery.
Upvotes: -2
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
Reputation: 48813
Try this:
return ("000000"+rgb.toString(16)).slice(-6);
// ^----returns last 6 chars
Upvotes: 3
Reputation: 5217
How about this:
//...
return (0x1000000 | rgb).toString(16).substring(1);
Upvotes: 8