当使用浮点数时,fillRect()不完全重叠 [英] fillRect() not overlapping exactly when float numbers are used
问题描述
以下代码( 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个白框而不是一个,那么问题就消失了.或者,如果您将白框的尺寸扩大了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()不完全重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!