block by njvack 02ad8efcb0d552b0230d

Color to hex and rgba converter

Full Screen

Simple canvas-based color converter

To answer this StackOverflow question I wrote this — a small solution based on a never-rendered <canvas> element. It fills a 1-pixel canvas with the provided fill-style, and then reads the RGBA values of that pixel. It will work with any CSS color – name, rgba(), hex, or even something more exotic like a gradient or pattern. Invalid colors are always returned as transparent black. Transparent colors are treated as painted on a newly-cleared canvas.

It’s been tested in modern-ish versions of IE, Chrome, Safari, and Firefox. The API is:

color_convert.to_hex(color)   # Converts color to a hex-based RGB triple; to_hex('red') returns '#ff0000'
color_convert.to_rgba(color)  # Converts color to an rgba() string; to_rgba('red') returns 'rgba(255,0,0,1)'

And you'll probably never want it, but you can also
color_convert.to_rgba_array(color)  # Converts color to a 4-element Uint8ClampedArray: [R, G, B, A]

Totally open-source. Call it BSD-licensed or whatever. It’s a toy.

index.html

color-convert.js