Uncaught SecurityError: Tainted canvases may not be exported

Today, I play with HTML5 canvas to load an image from a URL, then convert it to dataURL. Here a piece of my JavaScript ES6 code

const image = new Image()
const canvas = document.createElement('canvas')
let dataURL

image.onload = () => {
  canvas.getContext('2d').drawImage(image, 0, 0)
  dataURL = canvas.toDataURL()
}

image.src = 'http://placehold.it/300'

But when I run the code, I got this error message

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

That’s happen because of CORS. The solution is so simple. Just add crossOrigin="Anonymous" attribute to HTMLImageElement (image object), like so

const image = new Image()
const canvas = document.createElement('canvas')
let dataURL

image.crossOrigin = 'Anonymous'

image.onload = () => {
  canvas.getContext('2d').drawImage(image, 0, 0)
  dataURL = canvas.toDataURL()
}

image.src = 'http://placehold.it/300'

The problem solved.

References:

Iklan

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s