Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifically change stroke opacity but not color on canvas

I have a nice tidy script that cycles through colors and it works nicely with the #xxxxxx format, but I want to change the transparency. Is there a way to do that?

I'm referring to ctx.strokeStyle()

Here's the current code:

canvas.strokeStyle = '#' + (((16777215 / s.length) * i).toString(16));

It cycles through a for loop with i incremented by 1 each cycle and it's a part of a switch. The for loop looks like this: for(var i = 0; i < s.length; i++){}

like image 377
JVE999 Avatar asked Aug 15 '13 09:08

JVE999


2 Answers

You can change ctx.globalAlpha in range of 0 to 1 before drawing each element in opacity you need.

like image 199
Martin Tale Avatar answered Nov 14 '22 23:11

Martin Tale


Use ctx.globalAlpha like Martin Tale answered or rgba([0-255], [0-255], [0-255], [0-1]) format. So you need to convert the integer to individual rgb values:

var color = ((16777215 / s.length) * i);
var r = (color >> 16) & 255;
var g = (color >> 8) & 255;
var b = color & 255;

var alpha = 0.5;

canvas.strokeStyle = "rgba("+r+","+g+","+b+","+alpha+")";
like image 45
bitWorking Avatar answered Nov 14 '22 21:11

bitWorking