toDataURL Fails On HTML5 Canvas with embedded image

Another post, something new learnt… While trying to use olarks browser window sharing feature, we (the team) discovered the that the canvas image layer (a JS image stamped onto a canvas) wasn’t being rendered. A dig in the console and a conversation with the support identified this console message as the problem:

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

It seem’s that images that are pulled from a different domain to the actual page and rendered onto a canvas, “taint” the canvas. Tainted canvases can then not be exported as an image nor dataURL.

The solution (thankfully) was straight forward. By setting a crossOrigin attribute on the image we can override the default browser security.

var image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = url;

More information can be found on the Mozzila Developer Network. Its also worth pointing out that valid CORs headers had been previously setup on our Amazon S3 bucket.

Ben Squire

Read more posts by this author.

Leicestershire, United Kingdom https://squired.co.uk