pid
pid

Reputation: 11607

HTML5+JS canvas unexpected line style

As I get from previous experience and documentation online, the following code should produce two vertical lines, one red and the other green.

Instead, I get two green lines or whatever strokeStyle I set at last.

I can't see where this code is wrong. Furthermore, it may be my browser that somehow boggles things up.

The JS Fiddle and the code:

<html>
  <body>
    <canvas></canvas>
    <script>

      var cvs = document.getElementsByTagName("canvas")[0];
      var ctx = cvs.getContext("2d");

      ctx.strokeStyle = "#ff0000";
      ctx.moveTo(1, 0);
      ctx.lineTo(1, 10);
      ctx.stroke();

      ctx.strokeStyle = "#00ff00";
      ctx.moveTo(11, 0);
      ctx.lineTo(11, 10);
      ctx.stroke();

    </script>
  </body>
</html>

Upvotes: 1

Views: 82

Answers (2)

dougajmcdonald
dougajmcdonald

Reputation: 20047

You need to call closePath() after your first line and before the second one.

Note that it will return you to your starting point.

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/closePath

EDIT:

I'd made an assumption that both paths had been begun as the OP described the lines being the same colour rather than not drawing at all.

Interestingly in a small local test the lines do draw without any begin paths, but the first line is drawn twice with the colour from the intended second path.

The correct answer is to beginPath() and closePath() each time as shown below:

  ctx.beginPath();
  ctx.strokeStyle = "#ff0000";
  ctx.moveTo(1, 0);
  ctx.lineTo(1, 10);
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.strokeStyle = "#00ff00";
  ctx.moveTo(11, 0);
  ctx.lineTo(11, 10);
  ctx.stroke();
  ctx.closePath();

Upvotes: 1

alex
alex

Reputation: 490243

Use ctx.beginPath() when you start your new line (this will implicitly close your previous path).

jsFiddle.

Upvotes: 4

Related Questions