js画布弧中的粗笔画

问题描述

我试图在画布上画一条弧线。但由于某种原因,它并不顺利。请注意,我也在代码添加了一些 css 以及响应式元标记。请检查代码段。

这段代码给了我一个粗线条的弧

rough arc

有什么办法可以让它顺利吗?

现在添加一个片段。请注意,弧线是在 draw 函数中绘制的,我使用屏幕外画布将结果返回以减少绘制调用

window.onload = main;
let canvas;
let frame;

class Widget {
  canvas;
  parent;
  constructor() {
    this.canvas = document.createElement("canvas");
  }
}

class Frame extends Widget{
  constructor(parent) {
    super();
    this.canvas.style.display = "block";
    this.canvas.height = window.innerHeight;
    this.canvas.width = window.innerWidth;
    this.parent = parent;
    this.parent.appendChild(this.canvas);

    this.buffer = document.createElement("canvas");
    this.buffer.height = this.canvas.height;
    this.buffer.width = this.canvas.width;
  }

  blit() {
    let context = this.canvas.getContext("2d");
    context.drawImage(this.buffer,0);
  }
}


function main() {
  frame = new Frame(document.body);
  animation();
}

function animation() {
  draw(frame.buffer);
  frame.blit();
  window.requestAnimationFrame(animation);
}

function draw(canvas) {
  let ctx = canvas.getContext("2d");
  ctx.clearRect(0,canvas.width,canvas.height);
  ctx.fillRect(0,canvas.height);

  ctx.arc(100,100,2*Math.PI);
  ctx.linewidth = 1;
  ctx.strokeStyle = "red";
  ctx.stroke();
}
<!DOCTYPE html>
<html>
  <head>
    <Meta name="viewport" content="width=device-width,initial-scale=1">
  </head>

  <style>
    html,body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
    }
  </style><body></body></html>

解决方法

好吧,我找到了问题和解决方案。 我需要在我的 arc() 函数调用之前添加 beginPath()。

function draw(canvas) {
  let ctx = canvas.getContext("2d");
  ctx.clearRect(0,canvas.width,canvas.height);
  ctx.fillRect(0,canvas.height);

  // beginPath() is important!!!
  ctx.beginPath()
  //
  ctx.arc(100,100,2*Math.PI);
  ctx.lineWidth = 1;
  ctx.strokeStyle = "red";
  ctx.stroke();
}

在添加 beginPath() 之前:

before

添加 beginPath() 后:

after