@pbroom/color-kitConversion

rgbToHex

Convert sRGB (0-255) to a lowercase hex string: #rrggbb, or #rrggbbaa when alpha is below 1. Channels are rounded and clamped to 0-255.

functionimport { rgbToHex } from '@pbroom/color-kit';srgb.ts:134
function rgbToHex(rgb: Rgb): string;

Parameters

rgbRgb
sRGB color; fractional and out-of-range channels are allowed

Returns

stringHex string with a leading #

Throws

  • When any channel or alpha is not finite

Example

TypeScript
import { rgbToHex } from '@pbroom/color-kit';

rgbToHex({ r: 59, g: 130, b: 246, alpha: 1 }); // → '#3b82f6'
rgbToHex({ r: 59, g: 130, b: 246, alpha: 0.5 }); // → '#3b82f680'
rgbToHex({ r: 300, g: -5, b: 127.6, alpha: 1 }); // → '#ff0080'

See also