Tadas Stasiulionis
Tadas Stasiulionis

Reputation: 1316

HTML5 Canvas lines with increase margin

I'm playing with HTML5 Canvas and Javascript and find some interesting logic of drawing the lines. Maybe you can help me.

I want to draw lines with increased width, but when the width is too wide for a margin and couple lines becomes one, I want to add some margin of 1px. This happens after the i becomes 14

function draw5() {
  var ctx = document.getElementById('tutorial').getContext('2d');
  var increaseHorizontal = 0;
  for(var i = 0; i < 17; i++) {
    var lineWidthVar = 1 + i;
    if(i >= 14){
      increaseHorizontal += 1;
    }
    ctx.lineWidth = lineWidthVar;
    ctx.beginPath();
    ctx.moveTo(5 + i * (14 + increaseHorizontal), 5);
    ctx.lineTo(5 + i * (14 + increaseHorizontal), 140);
    ctx.stroke();
  }
}

draw5();

After I add the increaseHorizontal variable, which is 1,2,3, the drawing of line gets extra pixels to the x axis, after the 14th line, this is how it looks:

enter image description here

It seems strange, because when I hardcode 15 instead of (14 + increaseHorizontal), drawing looks nicer for the 15th line, but with overall increased value of x axis throughout the all lines.

I hope it is clear what I am saying, and I hope it is just a small mistake I am not thinking of.

Here is the whole code sample:

function draw5() {
        var ctx = document.getElementById('tutorial').getContext('2d');
        var increaseHorizontal = 0;
        for(var i = 0; i < 17; i++) {
          var lineWidthVar = 1 + i;
          if(i >= 14){
            increaseHorizontal += 1;
          }
          ctx.lineWidth = lineWidthVar;
          ctx.beginPath();
          ctx.moveTo(5 + i * (14 + increaseHorizontal), 5);
          ctx.lineTo(5 + i * (14 + increaseHorizontal), 140);
          ctx.stroke();
        }
      }

      draw5();
canvas {
        border: 2px solid #000;
      }
<canvas id="tutorial" width="300" height="150"></canvas>

Link to the jsfiddle

Upvotes: 1

Views: 312

Answers (1)

Nope
Nope

Reputation: 22329

You could keep track of the new start position and use that.

function draw5() {
  var ctx = document.getElementById('tutorial').getContext('2d');
  var startPosition = 0;
  var spacer = 5;
  for (var i = 0; i < 17; i++) {
    var lineWidthVar = 1 + i;
    startPosition = startPosition + lineWidthVar + spacer;

    ctx.lineWidth = lineWidthVar;
    ctx.beginPath();
    ctx.moveTo(startPosition, 5);
    ctx.lineTo(startPosition, 140);
    ctx.stroke();
  }
}

draw5();
canvas {
  border: 2px solid #000;
}
<canvas id="tutorial" width="300" height="150"></canvas>

Upvotes: 1

Related Questions