如何去除带有 canvas 的饼图中微弱的暗线?

How to get rid of faint dark lines in a pie chart with canvas?

我正在制作一个类似于饼图的色环,它由列表 [0..n] 制成。问题是每个切片之间有一些微弱的暗线。此处显示的绿色尤为明显。

这是我的代码:

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

const list = Array.from({ length: 100 }, (_, i) => i + 1); // generate list

context.fillStyle = '#000000';
context.fillRect(0, 0, canvas.width, canvas.height);
const center = [Math.floor(canvas.width / 2), Math.floor(canvas.height / 2)];
const radius = Math.min(center[0], center[1]);
let prevAngle = 0;
for (let i = 0; i < list.length; i++) {
  const hue = 255 - (list[i] / list.length) * 360;
  const color = `hsl(${hue},100%,50%)`;
  const angle = prevAngle + (1 / list.length) * Math.PI * 2;
  context.fillStyle = color;
  context.strokeStyle = color;
  context.beginPath();
  context.arc(center[0], center[1], radius, prevAngle, angle);
  context.lineTo(center[0], center[1]);
  context.fill();
  context.stroke();
  prevAngle = angle;
}
<canvas id="canvas" width="600" height="600"></canvas>

看起来这是由于子像素不精确造成的。您可以通过将线条稍微粗一点来使其不那么明显:

context.lineWidth = 1.5;

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

const list = Array.from({ length: 100 }, (_, i) => i + 1); // generate list

context.fillStyle = '#000';

context.lineWidth = 1.5; // <-------------

context.fillRect(0, 0, canvas.width, canvas.height);
const center = [Math.floor(canvas.width / 2), Math.floor(canvas.height / 2)];
const radius = Math.min(center[0], center[1]);
let prevAngle = 0;
for (let i = 0; i < list.length; i++) {
  const hue = 255 - (list[i] / list.length) * 360;
  const color = `hsl(${hue},100%,50%)`;
  const angle = prevAngle + (1 / list.length) * Math.PI * 2;
  context.fillStyle = color;
  context.strokeStyle = color;
  context.beginPath();
  context.arc(center[0], center[1], radius, prevAngle, angle);
  context.lineTo(center[0], center[1]);
  context.fill();
  context.stroke();
  prevAngle = angle;
}
<canvas id="canvas" width="600" height="600"></canvas>