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.
xxxxxxxxxx
<html>
<head>
<title>Color to hex and rgba conversion</title>
<script type="text/javascript" src="color-convert.js"></script>
<script type="text/javascript">
function update_rgba_hex() {
var cname = document.getElementById('cname').value;
document.getElementById('rgba').innerHTML = color_convert.to_rgba(cname);
document.getElementById('hex').innerHTML = color_convert.to_hex(cname);
var canvas, context;
canvas = document.getElementById('swatch');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = cname;
context.fillRect(0, 0, canvas.width, canvas.height);
}
</script>
</head>
<body>
<p>Enter a color <input size="30" id="cname" oninput="update_rgba_hex();"/> <button onclick="update_rgba_hex();">Check it</button></p>
<p>rgba: <code id="rgba"></code></p>
<p>hex: <code id="hex"></code></p>
<div>
<canvas id="swatch" width="50" height="50"></canvas>
</div>
</body>
</html>