javascript - Canvas 在浏览器之间是否有不同的抗锯齿功能?

标签 javascript firefox canvas chromium antialiasing

我正在编写一个生成图像的 javascript/canvas 脚本。我在浏览器之间遇到了截然不同的行为,我似乎无法理解为什么会发生这种情况或如何避免它。

我的代码本质上是这个版本,假设XY包含线的坐标:

//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 图像的一部分 Left: part of an image from firefox. Right: part of an image from chromium

左边的示例是所需的行为。

我的假设是这与两个浏览器中的抗锯齿有关,但我找不到讨论此行为的任何地方。我只找到一些例子,有人说如果你想要“像素图形”,你应该将坐标四舍五入为整数,但这是一个有点不同的问题。 '

问题:

  1. 你知道为什么会发生这种情况吗?
  2. 我能以某种方式避免它吗?

更新

  1. 这是现在代码的永久链接:https://bitbucket.org/inconvergent/orbitals_js/src/30f33d11461f4b307fe4a09048bd1b3af4960d31/index.htm

  2. 我写过 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/

相关文章:

css - Mozilla 和其他人之间的 Div Padding 差异

javascript - 相对指针位置

javascript - 如何让 Vue.js 对动态添加的数组属性的更改使用react?

javascript - 每次单击时都尝试单击 div 并在类中触发函数...在控制台中显示 TypeError

javascript - jqmobile listview中元素之间的间距相等

'overflow-y:auto' 的 CSS 问题在 Chrome 中产生了问题,但在 Firefox 中没有

jquery - bxslider/firefox 幻灯片对齐问题

android - Android 中的 Canvas 捏合缩放

javascript - 是否有任何关于让 HTML5 Canvas 在 IE9 中工作的提示?

javascript - 如何使用 Require.js 实现 TinyMCE?