为什么clearRect()没有完全清除fillRect()

Squ*_*rrl 3 javascript canvas

为什么clearRect()在这个例子中具有相同的值时没有完全清除fillRect()?

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";

setInterval(function(){
	let rect = {x:Math.random()*c.width, y:Math.random()*c.height}
	ctx.fillRect(rect.x, rect.y, 5, 5);
	ctx.clearRect(rect.x, rect.y, 5,5);
},500)
Run Code Online (Sandbox Code Playgroud)
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 5

因为抗锯齿.

您正在绘制非整数坐标,而您不能渲染半像素,因此像素颜色以一些透明度着色,以产生比像素更小像素的幻觉.

但是,clearRect()也受此抗锯齿处理,因此会留下一些半透明像素.

为了避免这种情况,请尝试在可能的情况下始终绘制像素整数,并且清除整个画布并重新绘制每帧所需的内容.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";

setInterval(function() {
  // clear all
  ctx.clearRect(0, 0, c.width, c.height);
  // redraw what needs to be
  let rect = {
    x: Math.random() * c.width,
    y: Math.random() * c.height
  }
  ctx.fillRect(rect.x, rect.y, 5, 5);
}, 500)
Run Code Online (Sandbox Code Playgroud)
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
Run Code Online (Sandbox Code Playgroud)