Failed to execute ‘toDataURL‘ on ‘HTMLCanvasElement‘: Tainted canvases may not be exported.
阿新 • • 發佈:2021-01-02
技術標籤:JSqrcode.react二維碼canvastoDataURL跨域
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,
重新執行,二維碼正常渲染。