Programmatically use RGBa values in fillStyle in <canvas>?

Viewed 83561

Using <canvas>, I want to set the RGBa value of the rectangle using a variable.

for example:

ctx.fillStyle = "rgba(32, 45, 21, 0.3)";

works fine, but using it with a variable:

var r_a =  0.3;
ctx.fillStyle = "rgba(32, 45, 21, r_a)";

doesn't work.

Apparently fillStyle only accepts a string. So how do I set a value of the rgba value using some variable instead of explicitly defining the values?

5 Answers

You just need to concatenate the r_a variable to build the string correctly:

var r_a = 0.3; 
ctx.fillStyle = "rgba(32, 45, 21, " + r_a + ")"; 
ctx.fillStyle = "rgba(32, 45, 21, "+r_a+")"; 

It is string concatenation.

I'm very late to the party but I had a similar problem and solved it in a slightly different way that may be useful.

Since I needed to reuse the fill colours at different alpha levels, I used the JavaScript replace method:

colurfill = "rgba(255, 255, 0, [[opacity]])";
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.5");
:
:
ctx.fillStyle = colurfill.replace("[[opacity]]", "0.75");

Obviously it doesn't have to be the alpha level that varies, it could be one of the other channels.

Related