user3074343 user3074343 - 7 months ago 777
Javascript Question

canvas.toDataURL() SecurityError

So I'm using google maps and I get the picture so it looks like this

<img id="staticMap"
src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">


I need to save it. I have found this:

function getBase64FromImageUrl(URL) {
var img = new Image();
img.src = URL;
img.onload = function() {

var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;

var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);

var dataURL = canvas.toDataURL("image/png");

alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));

};
}


But I get this problem:


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


I searched for fixes. I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work. Maybe I'm doing it the wrong way and there is a simpler way to do it? I'm trying to save this pic so that I can transfer the data to my server. So maybe someone did something like this and knows how to make
.toDataURL()
work as I need it?

Answer

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas. This is due to not having CORS approval. You can read more about this here, but it essentially means:

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

I suggest just passing the URL to your server-side language and using curl to download the image. Be careful to sanitise this though!

EDIT:

As this answer is still the accepted answer, you should check out @shadyshrif's answer, which is to use:

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

This will only work if you have the correct permissions, but will at least allow you to do what you want.