HTML画布上的第一行具有不同的宽度

时间:2017-01-18 21:35:54

标签: javascript html html5 html5-canvas

画布上的第一行有不同的宽度。我不明白为什么。有人可以帮忙吗?



var x = document.documentElement.clientWidth;
var y = document.documentElement.clientHeight;

var canvas = document.getElementById('myCanvas');

var context = canvas.getContext('2d');

context.lineWidth = 25;

context.beginPath();
context.moveTo(0, 0);
context.lineTo(x, 0);
context.strokeStyle = '#2f444f';
context.stroke();
context.closePath();

context.beginPath();
context.moveTo(0, 25);
context.lineTo(x, 25);
context.strokeStyle = '#ff0000';
context.stroke();
context.closePath();

context.beginPath();
context.moveTo(0, 50);
context.lineTo(x, 50);
context.strokeStyle = '#5f0000';
context.stroke();
context.closePath();

context.beginPath();
context.moveTo(0, 75);
context.lineTo(x, 75);
context.strokeStyle = '#9f0000';
context.stroke();
context.closePath();

<body>
<canvas id="myCanvas" width="1360" height="640" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

因为线条在y == 0时,宽度的一半落在画布之外,所以你得到一条更细的线条。

var x = document.documentElement.clientWidth;
var y = document.documentElement.clientHeight;

var canvas = document.getElementById('myCanvas');

      var context = canvas.getContext('2d');

      context.lineWidth = 25;
      var w2 = Math.floor(context.lineWidth / 2);

      context.beginPath();
      context.moveTo(0, w2);
      context.lineTo(x, w2);
      context.strokeStyle = '#2f444f';
      context.stroke();
      context.closePath();

	  context.beginPath();
      context.moveTo(0, 25 + w2);
      context.lineTo(x, 25 + w2);
      context.strokeStyle = '#ff0000';
      context.stroke();
      context.closePath();

	  context.beginPath();
      context.moveTo(0, 50 + w2);
      context.lineTo(x, 50 + w2);
      context.strokeStyle = '#5f0000';
      context.stroke();
      context.closePath();

      context.beginPath();
      context.moveTo(0, 75 + w2);
      context.lineTo(x, 75 + w2);
      context.strokeStyle = '#9f0000';
      context.stroke();
      context.closePath();
<body>
<canvas id="myCanvas" width="1360" height="640" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

</body>