1. 程式人生 > 其它 >Failed to execute ‘toDataURL‘ on ‘HTMLCanvasElement‘: Tainted canvases may not be exported.

Failed to execute ‘toDataURL‘ on ‘HTMLCanvasElement‘: Tainted canvases may not be exported.

技術標籤: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, // 中心是否為空心(被挖掘) }} />

當設定imageSettingssrc為某個CDN地址時,因為跨域的原因,出現了上文的錯誤。

解決:

我把要用到的資源下載到本地,之後匯入本專案中的資源:

import alipayIcon from "../../assets/img/alipay.ico";

src: alipayIcon,

重新執行,二維碼正常渲染。