gpt4 book ai didi

javascript - HTML5 Canvas — 线条太粗

转载 作者:行者123 更新时间:2023-12-02 15:50:30 28 4
gpt4 key购买 nike

这两天我一直在研究 HTML5 canvas 元素。我试图画一个迷宫,但我处于停滞状态。我画的线与 lineWidth 不一致属性(property)。它厚了~2px。

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

如果我没记错的话,如果你想让垂直线一致,x参数需要是0.5,对于水平线,y值需要是0.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

最佳答案

您不需要使用 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>

另一个选项(以避免 Angular 落中的“丢失像素”):绘制 2 条不同的路径并使用 8 的线宽作为“边框”

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();
canvas {
display: block;
margin: 0 auto;
margin-top: 50px;
/* border: 1px solid red; */
background: red;
}
<canvas id="c" width="200" height="200"></canvas>

关于javascript - HTML5 Canvas — 线条太粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31887401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com