简体   繁体   中英

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>

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

jsFiddle .

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM