html画布绘图显示通过

时间:2014-04-01 08:35:56

标签: javascript canvas

我确定在我找不到答案之前已经问过这个问题。

我想通过在顶部绘制另一个白色矩形来擦除黑色矩形的一部分,但是很多原始的黑色矩形显示为好像是平均的:

canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
context.globalAlpha = 1;
context.globalCompositeOperation = 'source-over';
context.strokeStyle = 'rgba(0,0,0,1)';
context.strokeRect(10,20,20,30);
context.strokeStyle = 'rgba(250,250,250,1)';
context.strokeRect(20,20,10,30);

js fiddle here我想看到的是左边是一个黑色的C,旁边是一个几乎是白色的矩形。相反,我看到单个黑色C,灰色反向C和两者之间的几乎白线:

Image of what is desired outcome and what is currently observed

1 个答案:

答案 0 :(得分:4)

起初我认为这是因为盒子根本不是黑色,而是看起来是灰色的,带有一点点alpha。所以,经过一些谷歌搜索,我发现了这个:Why isn't rectangle black in HTML 5 canvas?

基本上,你在圆形像素数上绘制一个1px宽边框的矩形,这意味着浏览器会尝试在半像素上绘制。您应该将位置设置为.5以避免此问题:

http://jsfiddle.net/VdGa6/2/

canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
// context.globalAlpha = 1;  // this is the default so it's not needed
// context.globalCompositeOperation = 'source-over';  // this is the default so it's not needed
context.strokeStyle = 'rgba(0,0,0,1)';
context.strokeRect(10.5,20.5,20,30);
context.strokeStyle = 'rgba(250,250,250,1)';
context.strokeRect(20.5,20.5,10,30);