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

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

My example would like to change fillStyle or strokeStyle over a canvas section whose color was random or more unknown. Is there a way to change alpha through another attribute or not passing anything to color (e.g. ctx.fillStyle = 'rgba (,, alphaValue)';)

+5
source share
2 answers

There are several ways.

globalAlpha .

, .

getImageData , , clearRect, globalAlpha, .

, globalAlpha . , , , .

, , globalAlpha, drawImage.

. , .

+3

RGB , , :

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

hexToRgb, , :

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;
}
+3

All Articles