color.js icon indicating copy to clipboard operation
color.js copied to clipboard

toString return complete hex color

Open HeiShuXianSheng opened this issue 2 years ago • 8 comments

how about a feature: new Color('red').toString({ format: 'hex' }); // #f00 add option to return #ff0000: eg: new Color('red').toString({ format: 'hex', complete: true }); // #ff0000

HeiShuXianSheng avatar Jan 06 '23 06:01 HeiShuXianSheng

We wouldn't be adding a separate option just to customize a format, but we should add something like format: "hex6", I've needed this too (for <input type="color"> in my case, but many places expect 6 digits)

LeaVerou avatar Jan 06 '23 12:01 LeaVerou

@svgeesus We should brainstorm about the name of this format (hex6? hex_6? hex_full? something else?), but the actual code changes should be very simple. I'll leave this open for a bit in case a new contributor wants to pick it up for their first PR.

LeaVerou avatar Jan 06 '23 12:01 LeaVerou

hex6 seems good because CSS Color 4 defines 3, 4, 6 and 8-digit hexadecimal forms and that naming allows all of them to be conveniently specified, eventually. (The 3 and 4 digit forms are lossy for most colors).

svgeesus avatar Jan 12 '23 17:01 svgeesus

@svgeesus The current "hex" format returns either 3, 4, 6, or 8 digit hex depending on whether alpha exists and whether there is an equivalent 3 or 4 digit hex. I guess this new format would return 4 or 8 characters (authors can always override alpha to get 6), so that would actually be a good argument for hex_full or something along these lines.

LeaVerou avatar Jan 12 '23 17:01 LeaVerou

It looks like this is already possible by passing in collapse: false-

let color = new Color("red").toString({format: 'hex', collapse: false})
// "#ff0000"

I'll defer to you all on whether this should be documented as is, or implemented in another way.

jamesnw avatar May 25 '23 17:05 jamesnw

Yes, I think I implemented that after this issue and forgot to close it! Still needs docs tho so maybe it should stay open.

LeaVerou avatar May 25 '23 22:05 LeaVerou

On the one hand, 'hex6' seems way easier to remember but on the other hand, a bird in the implementation is worth two in the ToDo. Or something. So, if there is a way to get there, adding documentation is easier.

svgeesus avatar May 27 '23 03:05 svgeesus

On the one hand, 'hex6' seems way easier to remember but on the other hand, a bird in the implementation is worth two in the ToDo. Or something. So, if there is a way to get there, adding documentation is easier.

Also, it's not always 6 characters. If you have alpha, it's 8.

LeaVerou avatar May 27 '23 18:05 LeaVerou