Convert RGB to RGBA

I am trying to play with HTML5 canvas, and I want to get the color of the fillStyle right from my CSS, but also with some transparency. When I use jQuery to read CSS style, a rgb value is returned instead of hex.

fillColor = $(".myClass").css("background-color"); // return rgb(x, x, x)

At first it look it's convinient to me that I don't need to convert it again, but I find that I cannot add the alpha to the RGB value, so I have to convert it into Hex, then convert it to RGBA with an alpha value.

function convertHexToRGB(hex)
{
    var red = hex.substr(1, 2), green = hex.substr(3, 2), blue = hex.substr(5, 2), alpha = arguments[1];
    color = "rgba(" + parseInt(red, 16) + "," + parseInt(green, 16) + "," + parseInt(blue, 16) + "," + alpha + ")";
    return color;
}

Now that make my code looks stink and inefficient, is there any way to add a alpha value to a RGB value. Or some function that converts RGB to RGBA?


Couldn't you just retrieve the opacity value from your css like this:

fillOpacity = $(".myClass").css("opacity"); // return 0.x

And then translate the opacity value into the 'A' channel you need:

var alpha = fillOpacity * 255;

And then append that to you rgb value (in int form)?

EDIT:

I should mention that the HTML5 canvas element works with bitmaps effectively so whilst you can do some combination bits and bobs, so there is no direct concept of layers, in that you can't (as far as I'm aware) tell a canvas element to be r,g,b,a because there is nothing for it to combine with underneath. Unless of course you are trying to place a semi-opaque canvas over a background image of some form. Or, combine an underlying image via say, multiply blending with your original CSS colour, to achieve the affect of a semi-transparent layer over an image.

链接地址: http://www.djcxy.com/p/87540.html

上一篇: 将十六进制转换为RGBa以获得背景不透明度

下一篇: 将RGB转换为RGBA