Reputation: 111
i want to set transparency for part of canvas can I use globalAlpha like for all canvas except rectangle i create in the canvas ?
Upvotes: 0
Views: 1185
Reputation:
If you mean how to make a rectangle transparent after you have a bunch of things drawn to the canvas you can do the following:
/// clear a rectangle to make canvas transparent
ctx.globalCompositeOperation = 'destination-out';
/// set alpha using a fill color with transparency
ctx.fillStyle = 'rgba(0,0,0,0.5)';
/// fill rectangle which now will become partly transparent all the way
ctx.fillRect(40, 40, 320, 320);
/// reset composite mode
ctx.globalCompositeOperation = 'source-over';
If this is not what you mean then you need to plan your drawings. As mentioned elsewhere you can set globalAlpha
before you draw something, draw it, then set globalAlpha
back before you draw the next. Each draw after setting globalAlpha
will be drawn with that alpha value (if the fill-style, stroke-style of image alpha uses transparency as well that will be a result of the two alpha values as they are multiplied).
globalCompositeOperation
decides how it will be drawn, for example on top of existing content, instead of and so forth (see an overview here).
Upvotes: 1
Reputation: 25954
As I've said in the comments twice, you just have to set the global alpha to what you want, draw what you want with that alpha, then change the global alpha to a new value, then draw what you want in that alpha. That can be done as follows
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(255, 0, 0,1)';
ctx.fillRect(0, 0, 150, 50);
ctx.globalAlpha = 0.2;
ctx.fillRect(150,50,150,50);
Upvotes: 0