CSS画布圈顺畅

时间:2017-01-09 16:39:15

标签: javascript css canvas

我有一个用画布绘制的圆圈,其中一个是另一个,问题是你可以看到后面的一个穿过前面的一个(红色轮廓)。有没有办法改善这个?

我唯一能想到的是增加顶部尺寸(lineWidth by pixel或2)以完全覆盖背面尺寸。

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var canvas2 = document.getElementById('myCanvas2');
var context2 = canvas2.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

for (var i = 0; i < 1; i++) {

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

  context.lineWidth = 25;
  context.strokeStyle = '#ff0000';
  context.stroke();
}

for (var i = 0; i < 1; i++) {

  context2.beginPath();
  context2.arc(centerX, centerY, radius, 0, 2.5, false);

  context2.lineWidth = 25;
  context2.strokeStyle = '#fff';
  context2.stroke();
}
#myCanvas,
#myCanvas2{
  position:absolute;
}
<canvas id="myCanvas" width="578" height="200"></canvas>
<canvas id="myCanvas2" width="578" height="200"></canvas>

https://jsfiddle.net/0zs2gqxk/3/

1 个答案:

答案 0 :(得分:0)

我想这是因为所谓的抗锯齿效果,这是浏览器中呈现的直接结果。

作为修复,您可以为红色弧指定起始角度,以便不会出现此问题 - 请参阅下面的演示(a已将background添加到body以供说明):

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var canvas2 = document.getElementById('myCanvas2');
var context2 = canvas2.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

for (var i = 0; i < 1; i++) {

  context.beginPath();
  context.arc(centerX, centerY, radius, 2.5, 2 * Math.PI, false); /* CHANGED HERE*/

  context.lineWidth = 25;
  context.strokeStyle = '#ff0000';
  context.stroke();
}

for (var i = 0; i < 1; i++) {

  context2.beginPath();
  context2.arc(centerX, centerY, radius, 0, 2.5, false);

  context2.lineWidth = 25;
  context2.strokeStyle = '#fff';
  context2.stroke();
}
body {
  background: #ddd;
}
#myCanvas,
#myCanvas2 {
  position: absolute;
}
<canvas id="myCanvas" width="578" height="200"></canvas>
<canvas id="myCanvas2" width="578" height="200"></canvas>