Ashwin Gupta Ashwin Gupta - 1 year ago 76
Javascript Question

Can I fill a rectangle with a transparent gradient javascript canvas?

I'm trying to overlay this black rectangle:

enter image description here

By filling another rectangle of the same size on top of it that has a semi-transparent, gradient paint (should look something like this):

enter image description here

I know I can do a transparent paint with the following:

g2d.fillStyle = "rgba(100, 3, 3, 0.5)";

I also know how to do a gradient paint:

var grd=g2d.createLinearGradient(0,0,200,0);

However, I do not know how to combine both the gradient and transparency properties together as one paint to use on my rectangle. How can I do this?

Answer Source

There are two ways:

Global alpha

Set global (consider it a "master alpha") right before drawing something:

ctx.globalAlpha = 0.5;  // [0, 1]
ctx.fillRect( ... );

Color alpha

Or define the colors themselves with alphas:

grd.addColorStop(0, "rgba(255,0,0, 0.5)");  // 50% alpha
grd.addColorStop(1, "rgba(0,0,255, 0.5)");

Worth to notice: if you use the latter approach and for example set 0% opacity on one end, the color will still matter as it is interpolated to the point where it becomes fully transparent. In the meanwhile the color definition will bleed through. I.e. don't just set black (unless black is what you need).