Saving canvas with CanvasRenderingContext2D filter

别等时光非礼了梦想. 提交于 2019-11-28 13:01:34

[Edit] : This bug has been fixed in FF52+ (current latest Nightly)
I let the answer and its workaround in case it helps someone some time.


This seems to be a bug in Firefox with filter-functions. Chrome 54 seems to handle it just right.

When a filter-function is passed as the value of ctx.filter, FF does taint the canvas, making all export methods unavailable (toDataURL included).

However, it seems pretty happy with svg filters, so one workaround, until this bug is fixed, is to use an svg filter along with the url(#yourSVGFilter) value type.

var img = new Image();
var c = document.createElement('canvas');
var ctx = c.getContext('2d');
document.body.appendChild(c);

btn.onclick = function() {
  var i = new Image();
  i.src = c.toDataURL();
  document.body.appendChild(i);
};

img.onload = function() {
  c.width = this.naturalWidth;
  c.height = this.naturalHeight;
  // this doesn't taint the canvas
  ctx.filter = 'url(#blurMe)';

  ctx.drawImage(img, 0, 0);
}

img.crossOrigin = 'anonymous';
img.src = 'https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png';
<svg width="0" height="0">
  <filter id="blurMe">
    <feGaussianBlur in="SourceGraphic" stdDeviation="2" />
  </filter>
</svg>

<button id="btn">call toDataURL()</button><br>

(And a fiddle that reproduces the problem for curious)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!