I came across this problem since I wanted to acceptparse any color string value and be able to addspecify an opacity, so I madewrote this quick jQuery pluginfunction that uses the native canvas on modern browsers. Seems to work just greatcanvas API.
var toRGBA = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 1;
canvas.height = 1;
return function (color) {
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
var data = context.getImageData(0, 0, 1, 1).data;
return {
r: data[0],
g: data[1],
b: data[2],
a: data[3]
};
};
}();
Edit Note about context.fillStyle
:
If parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value.
Turns out I can't figure out how to make it a proper jQuery plugin, so I'll just present it asHere's a regular function.Stack Snippet demo you can use to test inputs:
//accepts any value like '#ffffff', 'rgba(255,255,255,1)', 'hsl(0,100%,100%)', or 'white'
function toRGBA( c ) {
var
can = document.createElement( 'canvas' ),
ctx = can.getContext( '2d' );
can.width = can.height = 1;
ctx.fillStyle = c;
console.log( ctx.fillStyle ); //always css 6 digit hex color string, e.g. '#ffffff'
ctx.fillRect( 0, 0, 1, 1 ); //paint the canvas
var
img = ctx.getImageData( 0, 0, 1, 1 ),
data = img.data,
rgba = {
r: data[ 0 ], //0-255 red
g: data[ 1 ], //0-255 green
b: data[ 2 ], //0-255 blue
a: data[ 3 ] //0-255 opacity (0 being transparent, 255 being opaque)
};
return rgba;
};
var toRGBA = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 1;
canvas.height = 1;
return function (color) {
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
var data = context.getImageData(0, 0, 1, 1).data;
return {
r: data[0],
g: data[1],
b: data[2],
a: data[3]
};
};
}();
var inputs = document.getElementsByTagName('input');
function setColor() {
inputs[1].value = JSON.stringify(toRGBA(inputs[0].value));
document.body.style.backgroundColor = inputs[0].value;
}
inputs[0].addEventListener('input', setColor);
setColor();
input {
width: 200px;
margin: 0.5rem;
}
<input value="cyan" />
<input readonly="readonly" />