I am trying to paint an image on a canvas before I get its dataURL()
, but the data returned is like empty.
When I check it in the console, I see there is a lot of A
in the string : ("data:image/png;base64,iVBO..some random chars... bQhfoAAAAAAAAAA... a lot of A ...AAAASUVORK5CYII="
)
When I try to append the canvas to the document, nothing is drawn either and I don't have any error thrown in the console.
What is the problem here ?
Here is my code :
var img = new Image();
img.src = "http://somerandomWebsite/picture.png";
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0); // this doesn't seem to work
var dataURL = canvas.toDataURL(); // this will give me a lot of "A"
doSomething(dataURL);
Also, when doing a quick refresh, the image gets drawn correctly onto the canvas but I've got an error message in the console and dataURL
is empty.
The message in Firefox is : "SecurityError: The operation is insecure.",
in Chrome it is "Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.",
and on IE I just get "SecurityError".
What does it mean ?
You have to wait that your image has loaded before you can paint it on the canvas.
To do so, simply use the
load
event handler of your<img>
element :Also, for the canvas'
context.toDataURL()
andcontext.getImageData
to work properly, you have to get your image resource in a cross-origin compliant way, otherwise the canvas is "tainted" which means that any method to get pixels data will be blocked.img.crossOrigin
to"use-credentials"
.img.crossOrigin
to"anonymous"
.Nota Bene : CORS header is sent by the server, the
cross-origin
attribute will only let it know that you want to use CORS to get the image data, in no way you can circumvent it if the server is not set properly.Also some UserAgents (IE & Safari) still haven't implemented this attribute.
Edge Case : If some of your images are from your server and some are from a CORS compliant one, then you may want to use the
onerror
event handler which should fire if you set thecross-origin
attribute to"anonymous"
on a non CORS server.