Failed to execute ‘toDataURL‘ on ‘HTMLCanvasElement‘: Tainted canvases may not be exported.
Intro
我在使用qrcode.react测试使用文本生成二维码的功能。
当执行以下API时,报错:
let domTarget = event.target;
let text = domTarget.toDataURL("image/png"); // 本行报错
报错信息如下:
Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’:
Tainted canvases may not be exported.
是说受污染的canvac不可以被导出(调用toDataURL()
)
解决
组件渲染代码:
// npm i qrcode.react
import Qrcode from "qrcode.react";
// render:
<Qrcode
value={ this.state.value}
renderAs={ this.state.renderAs}
size={ this.state.size}
bgColor={ this.state.bgColor}
fgColor={ this.state.fgColor}
level={ this.state.level}
includeMargin={ this.state.includeMargin}
// 二维码中心的图片(log)的设置
imageSettings={ {
src: "https://img.alicdn.com/tfs/TB1qEwuzrj1gK0jSZFOXXc7GpXa-32-32.ico",
width: 50, // 百分比
height: 50,
excavate: true, // 中心是否为空心(被挖掘)
}}
/>
当设置imageSettings
的src
为某个CDN地址时,因为跨域的原因,出现了上文的错误。
解决:
我把要用到的资源下载到本地,之后导入本项目中的资源:
import alipayIcon from "../../assets/img/alipay.ico";
src: alipayIcon,
重新运行,二维码正常渲染。
还没有评论,来说两句吧...