Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can alpha transparency fill or stroke style be set separately from RGB in Canvas HTML5?

Tags:

html

canvas

alpha

In Canvas/HTML5, I know you can use RGBA to set color and alpha transparency for fillStyle or strokeStyle. You can also use just RGB to set color with no alpha channel. is there a way you can change the alpha value of an item without also supplying the color.

My example would be wanting to change the fillStyle or strokeStyle above a canvas section whose color was random or no longer known. Is there a way to change the alpha through another attribute or by passing nothing to the color (e.g. ctx.fillStyle = 'rgba(,,,alphaValue)';)

like image 898
InfiniteMonkeys Avatar asked Jun 04 '11 02:06

InfiniteMonkeys


2 Answers

There are a few ways.

First, the globalAlpha attribute of the context.

As you ask in the title, it will allow transparency to be set independently of fill or stroke.

You could then use the getImageData on a point to find out the color and save that info, clear that area with clearRect, set globalAlpha, and then redraw that area with the color you saved.

Of course, you don't need globalAlpha at all. You could also do the above and instead of setting global alpha, just modify the alpha of the color that you saved.

If you want to make a large, complex area of canvas more transparent, then you will want to change the globalAlpha and then draw the canvas onto itself using drawImage.

Here's an example of that. I draw two rectangles, then make a rectangular area between them more transparent.

like image 67
Simon Sarris Avatar answered Oct 04 '22 16:10

Simon Sarris


You can use a function to extract the RGB values from whatever is set for the style you are interested in, and then set it with the desired alpha:

var rgb = hexToRgb(canvasCtx.fillStyle);
canvasCtx.fillStyle = "rgba(" + rgb["r"] + "," +rgb["g"] + "," + rgb["b"] + ",0.2)";

You can use an hexToRgb function like this one, taken from this other answer:

function hexToRgb(hex) {
    // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, function(m, r, g, b) {
        return r + r + g + g + b + b;
    });

    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}
like image 35
palako Avatar answered Oct 04 '22 17:10

palako