Color Output
Convert XColor instances to various formats. All output methods are read-only operations and do not modify the instance.
Hex
toHex(allow3Char?, forceAlpha?)
Returns a hex string.
| Param | Type | Default | Description |
|---|---|---|---|
allow3Char | boolean | false | Allow shorthand 3-digit format (#f00) |
forceAlpha | boolean | false | Force 8-digit output (with alpha) |
xcolor('#ff0000').toHex() // '#ff0000'
xcolor('#ff0000').toHex(true) // '#f00'
xcolor('#ff0000').toHex(false, true) // '#ff0000ff'
xcolor('rgba(255,0,0,0.5)').toHex() // '#ff000080' (auto 8-digit when alpha < 1)Aliases: toHexString(), hex()
RGB
toRgb()
Returns a { r, g, b, a } object.
xcolor('#ff0000').toRgb() // { r: 255, g: 0, b: 0, a: 1 }Alias: toObject()
toRgbString()
Returns an rgb() or rgba() string. Automatically uses rgba() when alpha < 1.
xcolor('#ff0000').toRgbString() // 'rgb(255, 0, 0)'
xcolor('rgba(255,0,0,0.5)').toRgbString() // 'rgba(255, 0, 0, 0.5)'toRgbArray()
Returns a [r, g, b, a] array.
xcolor('#ff0000').toRgbArray() // [255, 0, 0, 1]HSL
toHsl()
Returns a { h, s, l, a } object.
xcolor('#ff0000').toHsl() // { h: 0, s: 100, l: 50, a: 1 }toHslString()
Returns an hsl() or hsla() string.
xcolor('#ff0000').toHslString() // 'hsl(0, 100%, 50%)'Number
toNumber()
Returns a 24-bit integer. Does not include alpha information.
xcolor('#ff0000').toNumber() // 16711680 (0xff0000)
xcolor('#0000ff').toNumber() // 255General Formatting
toString(format?)
Without arguments, the default output is:
- Has alpha (< 1) →
rgba()string - No alpha →
hexstring
Pass a format argument to output a specific format:
xcolor('#ff0000').toString() // '#ff0000'
xcolor('#ff0000').toString('rgb') // 'rgb(255, 0, 0)'
xcolor('#ff0000').toString('hsl') // 'hsl(0, 100%, 50%)'Alias: format()
Built-in Format Keys
| Key | Output |
|---|---|
'hex' | #ff0000 |
'hex3' | #f00 (allows shorthand) |
'hex8' | #ff0000ff (forces alpha) |
'rgb' | rgb(255, 0, 0) |
'hsl' | hsl(0, 100%, 50%) |
Plugins can extend additional formats. For example, after registering the cmyk plugin, you can use toString('cmyk').
Precision and round trips
| Output | Precision and alpha |
|---|---|
alpha() | Returns the stored alpha |
toRgb(), toHsl() and their array forms | Alpha preserves the stored precision. toHslArray() returns [h, s, l, a]. |
| RGB and HSL strings | Retain stored alpha. HSL string coordinates are rounded to integers. |
| Hex | Quantizes RGB and alpha to 8-bit channels |
toNumber() | Quantizes RGB and omits alpha |
For example, alpha 0.004 is returned as 0 in toRgb().a, and as 0.004 in toRgbString(). The useDecimal option retains fractional RGB channels in the instance. Each serializer still applies its own rules. Wide-gamut inputs are clipped when converted to the stored sRGB channels. For Lab/LCH round trips use the same reference white for parsing and serialization.
