stackdaemon
stackdaemon

Reputation: 349

Javascript canvas stroke opacity not applied to each lineto but rather continually over lines

It seems that my understanding of the javascript canvas strokestyle/line drawing is not up to par. I want to draw lines with a bit of transparency, but I fail to get the transparency applied to each and every line (segment) and instead get it sort of applied as a gradient over all the lines I've drawn...

Example code:

var c = document.getElementsByTagName('canvas')[0];
var a = c.getContext('2d');

WIDTH = 400;
HEIGHT = 400;
c.width = WIDTH;
c.height = HEIGHT;;

function applyGrid()
{
    a.fillStyle = "000000";
    a.lineWidth = 2;
    a.fillRect(0, 0, WIDTH, HEIGHT);

    a.strokeStyle = "rgba(0,200,200,0.1)";
   for (var x = 0; x <= WIDTH; x += 50)
   {
      a.moveTo(x, 0);
      a.lineTo(x, HEIGHT);
      a.stroke();
    }

}
applyGrid();​

See example code and (wrong) result here: http://jsfiddle.net/zKWaT/3/ I want all vertical lines to have the transparency of the rightmost line, but instead they gradually fade.

I guess I have missed something basic about how lineTo and stroke works, but having looked at examples here and there I haven't found something revealing... tt.

Thanks for your input!

Upvotes: 3

Views: 3943

Answers (1)

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

inside your for loop add a.beginPath() to start a new line on each loop. Otherwise you're just extending and stroking the same line over and over.

var c = document.getElementsByTagName('canvas')[0];
var a = c.getContext('2d');

WIDTH = 400;
HEIGHT = 400;
c.width = WIDTH;
c.height = HEIGHT;;

function applyGrid()
{
    a.fillStyle = "000000";
    a.lineWidth = 2;
    a.fillRect(0, 0, WIDTH, HEIGHT);

    a.strokeStyle = "rgba(0,200,200,0.1)";
   for (var x = 0; x <= WIDTH; x += 50)
   {
      a.beginPath(); //ADD THIS
      a.moveTo(x, 0);
      a.lineTo(x, HEIGHT);
      a.stroke();
    }

}
applyGrid();​

Upvotes: 1

Related Questions