CanvasContext2D drawImage() issue [onload and CORS]
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 ?
javascript canvas html5-canvas
add a comment |
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 ?
javascript canvas html5-canvas
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02
add a comment |
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 ?
javascript canvas html5-canvas
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 ?
javascript canvas html5-canvas
javascript canvas html5-canvas
edited Nov 6 '15 at 17:30
community wiki
3 revs
Kaiido
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02
add a comment |
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02
add a comment |
1 Answer
1
active
oldest
votes
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 :
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
Also, for the canvas' context.toDataURL()
and context.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.
- If your image comes from the same server, no problem.
- If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the
img.crossOrigin
to"use-credentials"
. - If the server does allow anonymous requests, you can set the
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 the cross-origin
attribute to "anonymous"
on a non CORS server.
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32880641%2fcanvascontext2d-drawimage-issue-onload-and-cors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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 :
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
Also, for the canvas' context.toDataURL()
and context.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.
- If your image comes from the same server, no problem.
- If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the
img.crossOrigin
to"use-credentials"
. - If the server does allow anonymous requests, you can set the
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 the cross-origin
attribute to "anonymous"
on a non CORS server.
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
add a comment |
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 :
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
Also, for the canvas' context.toDataURL()
and context.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.
- If your image comes from the same server, no problem.
- If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the
img.crossOrigin
to"use-credentials"
. - If the server does allow anonymous requests, you can set the
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 the cross-origin
attribute to "anonymous"
on a non CORS server.
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
add a comment |
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 :
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
Also, for the canvas' context.toDataURL()
and context.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.
- If your image comes from the same server, no problem.
- If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the
img.crossOrigin
to"use-credentials"
. - If the server does allow anonymous requests, you can set the
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 the cross-origin
attribute to "anonymous"
on a non CORS server.
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
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 :
// create a new image
var img = new Image();
// declare a function to call once the image has loaded
img.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0,0);
var dataURL = canvas.toDataURL();
// now you can do something with the dataURL
doSomething(dataURL);
}
// now set the image's src
img.src = "http://somerandomWebsite/picture.png";
Also, for the canvas' context.toDataURL()
and context.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.
- If your image comes from the same server, no problem.
- If your image is served from an external server, be sure that it allows yours in its cross-origin headers and set the
img.crossOrigin
to"use-credentials"
. - If the server does allow anonymous requests, you can set the
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 the cross-origin
attribute to "anonymous"
on a non CORS server.
function corsError(){
this.crossOrigin='';
this.src='';
this.removeEventListener('error', corsError, false);
}
img.addEventListener('error', corsError, false);
edited Oct 5 '15 at 5:21
community wiki
3 revs, 2 users 98%
Kaiido
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32880641%2fcanvascontext2d-drawimage-issue-onload-and-cors%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
This post is meant to be a canonical one for the 20 or so a week we get about this particular issue. Please let me know if it can be improved.
– Kaiido
Oct 1 '15 at 6:20
Isn't just the point of loading images before doing anything with them more relevant ? And if you think useful to refer to toDataURL, you should mention the (possible) CORS issue. Anyway +1 for the wiki idea / effort.
– GameAlchemist
Oct 1 '15 at 9:04
@GameAlchemist you're right, I tried to combine both issues, since they're really similar and often come in pair. I talked about the CORS issue in the answer. Don't know how search engines will deal with that though, maybe I should add the "canvas is tainted" message error into the question. Anyway, I asked that the question is converted to wiki too, this way, you'll be able to edit it.
– Kaiido
Oct 1 '15 at 14:02