Re: [css-color] Exposing browser color parsing to JS

On Mon, Jul 7, 2014 at 5:48 PM, Simon Sapin <simon.sapin@exyr.org> wrote:
> On 08/07/14 00:27, Tab Atkins Jr. wrote:
>> One of my coworkers brought my attention to
>>
>> <http://code.stephenmorley.org/javascript/colour-handling-and-processing/>,
>> a library that does basic color manipulation and
>> parsing/serialization.  I've seen this sort of thing multiple times,
>> and even wrote my own (<http://www.xanthir.com/etc/color.js>).  I've
>> also had to write a fairly complete color parser in PHP in the past.
>>
>> Given that most/all of this machinery already exists in the browser,
>> it's kinda sad that people have to keep reinventing it.  What would
>> y'all think about introducing a bit of a helper for this kind of
>> thing, that exposes all of the parsing and serialization the browser
>> does, and is easily extensible so authors can use it as the basis for
>> their own color-using code?
>
> A trick I’ve seen in stuff made by Lea Verou to use the browser’s color
> parsing code is to set e.g. someElement.style.color to the string to parse,
> then get getComputedStyle(someElement).color, which is in rgb() or rgba()
> format and much easier to hand-parse.

Yup, but that's a pretty dumb trick.  It also means you still have to
do conversions yourself if you want it in some other format.

(Related to that, if serialization isn't consistent, is the "draw into
a canvas, get back imagedata" trick, which gives you the color in a
guaranteed 4-element array of octets.)

Ultimately, lots of unit conversions are done in the same way, via
some off-screen element.  But I think color parsing/manipulation is
sufficiently common and sufficiently more complex to possibly justify
this kind of helper, while other things might not get one until the
real OM comes along.

(That said, I could probably go for a good length converter, with the
ability to provide element and property context, ahead of the real OM
as well.)

~TJ

Received on Tuesday, 8 July 2014 00:58:35 UTC