【问题标题】:HTML5 Canvas antialiasHTML5 Canvas 抗锯齿
【发布时间】:2016-12-13 09:32:31
【问题描述】:

Example

大家好。 我有一个红色背景的画布。 在它上面,我有一排排的盒子,它们彼此紧挨着。 每个盒子都从前一个盒子结束的地方开始,并且它们都具有相同的偏斜。 所以边之间不应该有任何间隙,但正如您在示例中看到的那样,存在间隙。

有谁知道为什么会发生这种情况,以及如何摆脱它。

console.clear();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var world = {
  centerY: canvas.height / 2,
  centerX: canvas.width / 2
}
var rowCount = 14;
var box = {
  width: 20,
  height: 20,
  skew: 10
}

function drawBox(x, y, id) {
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x + box.width, y);
  ctx.lineTo(x + box.width + box.skew, y - 20);
  ctx.lineTo(x + box.skew, y - box.height);
  ctx.lineTo(x, y);
  ctx.closePath();
  ctx.clip();
  ctx.clearRect(0,0, canvas.width, canvas.height);
  ctx.fillStyle = id % 2 == 0 ? 'lightgray' : 'darkgray';
  ctx.fill();
  ctx.restore();

}

for (var i = 0; i < 112; i++) {
  var k = Math.floor(i / rowCount) * rowCount;
  console.log(k);
  drawBox(i * box.width - (k * box.width), Math.floor(i / rowCount) * box.height, i)
}
#canvas {
  background-color: red;
  width: 800px;
  height: 600px;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <canvas id="canvas">

  </canvas>
</body>

</html>

【问题讨论】:

  • 在每个方框的右边加一个像素,洞就消失了
  • @Blindman67 在应用ctx.clearRect(0,0, canvas.width, canvas.height); 时不起作用。
  • 你更新jsBin了吗?
  • 是的,我已经更新了 jsBin。
  • 不要使用透明的。您永远无法在画布上获得完美的接缝,因此您必须使用它。我不明白为什么在填充该颜色时需要清除。

标签: javascript html canvas antialiasing


【解决方案1】:

在函数drawBox中更新:

  ctx.lineTo(x+box.width, y);
  ctx.lineTo(x+box.width + box.skew, y - 20);

ctx.lineTo(x+box.width+1, y);
ctx.lineTo(x+box.width + box.skew +1, y - 20);

【讨论】:

  • 对不起,我忘了在ctx.clip()之后添加ctx.clearRect(0,0, canvas.width, canvas.height);
猜你喜欢
  • 1970-01-01
  • 2012-08-23
  • 2011-08-27
  • 2014-02-18
  • 2011-05-31
  • 2011-05-14
  • 1970-01-01
  • 2016-06-28
  • 2011-07-05
相关资源
最近更新 更多