我正在编写一个生成图像的 javascript/canvas 脚本。我在浏览器之间遇到了截然不同的行为,我似乎无法理解为什么会发生这种情况或如何避免它。
我的代码本质上是这个版本,假设X
和Y
包含线的坐标:
//this section of code is repeated a large number of times.
CTX.strokeStyle = 'rgba(0,0,0,0.05)';
CTX.lineWidth = 1 ;
for(var i = 0;i<NUM;i++){
for(var j = 0;j<NUM,j++){
if (!F[i*NUM+j]){
// i and j are not friends
// and should not have a line between them
continue;
}
var ax = X[i];
var ay = Y[i];
var bx = X[j];
var by = Y[j];
CTX.beginPath();
CTX.moveTo(ax,ay);
CTX.lineTo(bx,by);
//CTX.closePath(); // not needed. but removing does not fix problem.
CTX.stroke();
}
}
请注意,线条紧密重叠,这就是我将 alpha 值设置得如此低的原因。图像应该逐渐曝光。
这是显示该行为的图像:
左:来自 Firefox 的图像的一部分。右:Chromium 图像的一部分
左边的示例是所需的行为。
我的假设是这与两个浏览器中的抗锯齿有关,但我找不到讨论此行为的任何地方。我只找到一些例子,有人说如果你想要“像素图形”,你应该将坐标四舍五入为整数,但这是一个有点不同的问题。 '
问题:
- 你知道为什么会发生这种情况吗?
- 我能以某种方式避免它吗?
更新
这是现在代码的永久链接:https://bitbucket.org/inconvergent/orbitals_js/src/30f33d11461f4b307fe4a09048bd1b3af4960d31/index.htm
我写过 chrome。事实证明,当我遇到这个问题时,我实际上正在使用 Chrome 。在 ubuntu 13.10 上。将在我的机器上用 chrome 进行测试并发回。
最佳答案
Canvas 一团糟,但有一些解决方案:
像素操作
To allow for sub-pixel drawings, all browser implementations of canvas employ anti-aliasing (although this does not seem to be a requirement in the HTML5 spec). Anti-aliasing can be important to keep in mind if you want to draw crisp lines and notice the result looks blurred. To work around this you will need to either round to integer values or offset by half a pixel depending on if you’re drawing fills or strokes.
双缓冲
子像素渲染
创建模式
FWIW, there is a workaround to get anti-aliased clipped edges for drawing an image to a canvas. Instead of this: ctx.beginPath(); (draw a fancy path) ctx.clip(); ctx.drawImage(myImage, ...); Do this: ctx.fillStyle = ctx.createPattern(image); ctx.beginPath(); (draw a fancy path)
引用文献
关于javascript - Canvas 在浏览器之间是否有不同的抗锯齿功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414535/