1
votes

I'm trying to draw different rectangular designs using setLineDash and lineDashOffset(HTML5 Canvas-2d Context). But Solid lines are drawn instead of dashed lines. Please help.

Points to be noted:

  1. Canvas Scaling is done.
  2. drawLine API is used for drawing lines.
  3. I'm using different integer points to draw lines.
  4. setLineDash([3,2]). Strictly, dashed thickness is "3" and space between them is "2" should be used.

`

this.context.setLineDash([3,2]);
this.context.lineDashOffset = 2;  
drawLine(300,9.5,570,10);
drawLine(300,9.5,300,100);
drawLine(300,99.5,570,100);
drawLine(570,9.5,570,100);`

My Complete code for your reference: Codepen Link

Inspired from: Document Link

enter image description here

1
It would be great if you could include drawLine in your question, since this was actually where the problem came from. - Kaiido

1 Answers

1
votes

This happens because you close the path using closePath().

This method doesn't say "the path declaration is over", it says, "make my path an enclosed path", which means it will lineTo the last entrance point in the path. Doing so and depending on the line's length, the second line may have its own dashes cover the holes of the first line.

const context = canvas.getContext("2d");

function drawLine(x1, y1, x2, y2, mode) {
  context.beginPath();
  context.moveTo(x1, y1);
  context.lineTo(x2, y2);
  switch (mode) {
    case "closePath":
      context.closePath();
    case "lineTo":
      context.lineTo(x1, y1);
  }
  context.stroke();
}
context.lineWidth = 2;
context.setLineDash([3, 2]);

context.strokeStyle = "red";
drawLine(30, 9.5, 30, 100, "closePath");
context.strokeStyle = "blue";
drawLine(60, 9.5, 60, 100, "lineTo");
context.strokeStyle = "green";
drawLine(90, 9.5, 90, 100, "");
<canvas id="canvas"></canvas>

And to avoid this, don't call closePath().