color-js / color.js

Color conversion & manipulation library by the editors of the CSS Color specifications
https://colorjs.io
MIT License
1.81k stars 80 forks source link

Trouble converting to hex #557

Open keithjgrant opened 3 weeks ago

keithjgrant commented 3 weeks ago

related: #246

I think I'm totally misunderstanding something here. I can't figure out how to convert colors defined in OKLCH to hex. It seems to me this should do it, but it just ignores the requested format (no matter which format I try).

new Color('oklch', [0.5, 0.17, 60], 1).toGamut({space: 'srgb'}).toString({format: 'hex'})
>> "oklch(50.183% 0.12747 52.941)" 

Using the to() function instead works for most formats, but not for hex:

new Color('oklch', [0.5, 0.17, 60], 1).toGamut({space: 'srgb'}).to('hsl').toString();
>> "hsl(29.068 100% 30.171%)"
new Color('oklch', [0.5, 0.17, 60], 1).toGamut({space: 'srgb'}).to('hex').toString();
>> Uncaught TypeError: No color space found with id = "hex"

I've tried a number of other approaches, both with and without a toGamut() call, but I think I'm fundamentally misunderstanding something about how or when the library converts between color spaces or something.

keithjgrant commented 3 weeks ago

okay, this works:

new Color('oklch(50% 0.17 60)').toGamut({space: 'srgb'}).to('srgb').toString({format: 'hex'})
>> "#9a4b00"

I think I needed to map the gamut, then convert to srgb color space before I can format as hex. Am I understanding that correctly? to needs an actual color space, not an output format, which makes sense now that I've stepped back and thought about it further.

This issue can probably be closed

LeaVerou commented 3 weeks ago

Your original example should work with the dev branch, which will soon be v0.6.0. Could you try it and let us know if it doesn’t?

keithjgrant commented 3 weeks ago

do I need to pull down the repo and compile to access that, or is there a bundled version available somewhere for quicker access?

LeaVerou commented 3 weeks ago

You can just import directly from the colorjs.io website as described here, that always uses the dev branch: https://colorjs.io/get/