Converts the values of RGB components to a hexadecimal color code.
<<
) and Number.prototype.toString()
.String.prototype.padStart()
to get a 6-digit hexadecimal value.const RGBToHex = (r, g, b) =>
((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
RGBToHex(255, 165, 1); // 'ffa501'
Snippet collection
Working with color in JavaScript requires some understanding of color formats and conversions. Luckily, this snippet collection's got you covered.
JavaScript, String
Converts a color code to an rgb()
or rgba()
string if alpha value is provided.
JavaScript, String
Converts an rgb()
color string to an object with the values of each color.
JavaScript, String
Extends a 3-digit color code to a 6-digit color code.