以下代码 (jsFiddle) 在画布上的随机点绘制一个红色方块,注意擦除前一个(通过用 ctx.fillRect()
填充一个白色方块:
The following code (jsFiddle) draws a red square at random points on a canvas taking care to erase the previous one (by filling a white square over it with ctx.fillRect()
:
<html>
<canvas id='canvas' width=300 height=300/>
<script>
const ctx = document.getElementById('canvas').getContext('2d');
let prevRect = null;
for (let i = 0 ; i < 10; i++) {
if (prevRect != null) {
ctx.fillStyle='white';
ctx.fillRect(prevRect.x, prevRect.y, 50, 50);
}
ctx.fillStyle='red';
const newRect = {x: Math.random()*(300-50), y: Math.random()*(300-50)};
ctx.fillRect(newRect.x, newRect.y, 50, 50);
prevRect = newRect;
}
</script>
</html>
代码未能完全擦除前一个方块,并且屏幕上仍保留有伪影.相反,如果我执行以下操作:
The code fails to completely erase the previous square and artifacts remain on the screen. If, instead, I do the following:
const newRect = {x: Math.floor(Math.random()*(300-50)), y: Math.floor(Math.random()*(300-50))};
...然后一切都按预期进行.
... then everything works as intended.
我的问题是为什么.似乎完全没有必要截断,因为我将值保留在 prevRect
中,因此对 fillRect()
的两个调用使用完全相同的坐标(即使使用浮点数)所以这两个正方形应该总是完美对齐.
My question is why. It seems totally unnecessary that I have to truncate as I keep the values in the prevRect
so the two calls to fillRect()
use exactly the same coordinates (even when using floats) and so the two squares should always perfectly align.
问题源于在画布上绘制事物的基本方式.绘制正方形时,形状的边缘会略微羽化".因此,当您在前一个红色框上绘制白色框时,红色的残余部分会渗入半透明边缘.
The problem stems from the basic way that things are drawn on a canvas. When you draw a square, the edges of the shape are slightly "feathered". Thus when you draw the white box over the previous red box, the remnants of red bleed into the semi-transparent edge.
如果您绘制 10 个白框而不是 1 个,问题就消失了.或者,如果你让白框可能大 0.5 像素,那可能会有所帮助.
If you draw 10 white boxes instead of one, the problem goes away. Or if you make the white box probably 0.5 pixels larger, that would likely help.
const ctx = document.getElementById('canvas').getContext('2d');
let prevRect = null;
for (let i = 0 ; i < 10; i++) {
if (prevRect != null) {
ctx.fillStyle='white';
ctx.fillRect(prevRect.x - 0.75, prevRect.y - 0.75, 51.5, 51.5);
}
ctx.fillStyle='red';
const newRect = {x: Math.random()*(300-50), y: Math.random()*(300-50)};
ctx.fillRect(newRect.x, newRect.y, 50, 50);
prevRect = newRect;
}
body, html { padding: 0; }
canvas { border: 1px solid black; }
<canvas id=canvas height=300 width=300></canvas>
看起来每边大 0.75 效果很好,但它肯定是画布逻辑"大小与实际屏幕大小的函数.
Looks like 0.75 bigger on each side works pretty well, but it's certain to be a function of canvas "logical" size vs. actual screen size.
这篇关于使用浮点数时,fillRect() 不完全重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!