解决Canvas中getImageData的图片跨域问题

情况

this.bg = new Image();
this.bg.onload = handleOnload;
this.bg.src = this.bgSrc;
...
let data2d = this.ctx.getImageData(0, 0, this.touch.cw, this.touch.ch).data;

报错

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

解决方法

this.bg = new Image();
this.bg.onload = handleOnload;
this.bg.setAttribute('crossOrigin', 'anonymous');
this.bg.src = this.bgSrc;

crossOrigin的设置在src的赋值之后时,安卓下没问题,Safari下仍会报错,所以需要确定好这两句代码的前后顺序。

参考链接

MDN img 标签

原文链接:segmentfault.com

上一篇:js超大整数相加函数
下一篇:node 核心模块学习之 Buffer

相关推荐

官方社区

扫码加入 JavaScript 社区