HTML5画布 - 线太粗

时间:2015-08-07 22:15:11

标签: javascript html5 canvas

过去两天我一直在玩HTML5 canvas元素。我试图画一个迷宫,但我是一个停滞不前的人。我绘制的线与lineWidth属性不一致。它厚~2px。

我熟悉canvas元素的半像素问题,你需要从0.5开始,但我不知道我需要把0.5放在哪里在我的代码中。

如果我没有弄错,如果你想让垂直线保持一致,那么x参数必须是.5而对于水平线,y值必须是.5?

enter image description here

    var canvas = document.getElementById("c"),
    c = canvas.getContext("2d"),
    w = canvas.width,
    h = canvas.height,
    hallwayWidth = w * 0.10; /*18px*/

c.beginPath();
c.lineWidth = 4;
c.moveTo(0, 0);
c.lineTo(w / 3, 0);
c.moveTo(0, 0);
c.lineTo(0, h);
c.moveTo(w, 0);
c.lineTo(w, h);
c.moveTo(w / 3 + hallwayWidth, 0);
c.lineTo(w, 0);
c.moveTo(0, h);
c.lineTo(w / 2, h);
c.moveTo(w / 2 + hallwayWidth, h);
c.lineTo(w, h);

/*code for thick line*/
c.moveTo(hallwayWidth, 0);
c.lineTo(hallwayWidth, w / 3);

c.stroke();

Here's the link to the code

1 个答案:

答案 0 :(得分:2)

您不需要使用0.5,当lineWidth为4时,您必须使用:

  • 2代替0
  • (w-2)代替w
  • (h-2)代替h



var canvas = document.getElementById("c"),
	    c = canvas.getContext("2d"),
	    w = canvas.width,
	    h = canvas.height,
	    hallwayWidth = w * 0.10, /*18px*/
        l = 2;

	c.beginPath();
	c.lineWidth = l*2;
	c.moveTo(l,l);
	c.lineTo(w / 3, l);
	c.moveTo(l, l);
	c.lineTo(l, h-l);
	c.moveTo(w-l, l);
	c.lineTo(w-l, h-l);
	c.moveTo(w / 3 + hallwayWidth, l);
	c.lineTo(w-l, l);
	c.moveTo(l, h-l);
	c.lineTo(w / 2, h-l);
	c.moveTo(w / 2 + hallwayWidth, h-l);
	c.lineTo(w-l, h-l);

    /*code for thick line*/
    
	c.moveTo(hallwayWidth, l);
    c.lineTo(hallwayWidth, w / 3);

	c.stroke();

canvas {
    display: block;
    margin: 0 auto;
    margin-top: 50px;
    /* border: 1px solid red; */
    background:red;
}

<canvas id="c" width="200" height="200"></canvas>
&#13;
&#13;
&#13;

另一种选择(避免&#34;丢失像素&#34;在角落里):绘制2条不同的路径并用于&#34;边界&#34; lineWidth为8

&#13;
&#13;
var canvas = document.getElementById("c"),
  c = canvas.getContext("2d"),
  w = canvas.width,
  h = canvas.height,
  hallwayWidth = w * 0.10; /*18px*/

c.beginPath();
c.lineWidth = 8;
c.moveTo(0, 0);
c.lineTo(w / 3, 0);
c.moveTo(0, 0);
c.lineTo(0, h);
c.moveTo(w, 0);
c.lineTo(w, h);
c.moveTo(w / 3 + hallwayWidth, 0);
c.lineTo(w, 0);
c.moveTo(0, h);
c.lineTo(w / 2, h);
c.moveTo(w / 2 + hallwayWidth, h);
c.lineTo(w, h);
c.stroke();
/*code for thick line*/
c.beginPath();
c.lineWidth = 4;
c.moveTo(hallwayWidth, 0);
c.lineTo(hallwayWidth, w / 3);
c.stroke();
&#13;
canvas {
  display: block;
  margin: 0 auto;
  margin-top: 50px;
  /* border: 1px solid red; */
  background: red;
}
&#13;
<canvas id="c" width="200" height="200"></canvas>
&#13;
&#13;
&#13;