当lineWidth未设置为1时,HTML Canvas的行位置不正确

时间:2020-05-28 16:43:14

标签: javascript html canvas drawing

  function drawModule() {
    const lineWidth = 1
    context.lineWidth = lineWidth
    context.translate(0.5, 0.5)

    for (let k = 0; k < self.geometryParsed.length; k++) {
      const geometry = self.geometryParsed[k].geom
      const type = self.geometryParsed[k].typ

      context.beginPath()
      context.strokeStyle = self.unitMixTable[type]
      context.moveTo(
        Math.round(geometry[0].x),
        Math.round(geometry[0].y)
      )
      for (let i = 1; i < geometry.length; i++) {
        context.lineTo(
          Math.round(geometry[i].x),
          Math.round(geometry[i].y)
        )
        context.stroke()
      }
      context.closePath()
      context.fillStyle = 'white'
      context.fill()
    }
    context.translate(-0.5, -0.5)
  }

这是我用来在画布上绘制一些多边形的代码,它可以按预期工作,不会出现问题。但是,例如,当lineWidth为2时,线条的位置和不透明度会稍微失真。

结果图片:

lineWidth = 1

lineWidth = 2

当lineWidth为2时,您会在图中的红色圆圈中看到,即使它们共享相同的x点,它们也不会对齐。而且在每个组的最右边的矩形中,线条的颜色也不相同。

可能是什么问题?我有什么想念的吗?预先感谢!

复制:https://codepen.io/coldsewoo/pen/mdeZBev

1 个答案:

答案 0 :(得分:0)

填补是您问题的根本原因

const geometryParsed = [
  {
    geom: [{ x:78, y:132 }, { x:59, y:132 }, { x:59, y:183 }, { x:78, y:183 }, { x:78, y:132 }]
  },
  {
    geom: [{ x:97, y:132 }, { x:78, y:132 }, { x:78, y:166 }, { x:97, y:166 }, { x:97, y:132 }]
  },
];

const canv = document.getElementById("canvas");
const context = canv.getContext("2d");

context.translate(-50, -100)
context.lineWidth = 2;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);    
  }
  context.stroke();
}

context.translate(80, 0)
context.lineWidth = 4;
for (let k = 0; k < geometryParsed.length; k++) {
  const geometry = geometryParsed[k].geom;
  context.beginPath();
  context.moveTo(geometry[0].x, geometry[0].y);
  for (let i = 1; i < geometry.length; i++) {
    context.lineTo(geometry[i].x, geometry[i].y);
  }
  context.stroke();
  context.fillStyle = "white";
  context.fill();
}
<canvas id="canvas" width="476px" height="170px"></canvas>