Reputation: 79
I'm working on a page where you will be able to draw images on a canvas. You have 6 options of images, and when you are done I want people to able to save their creation.
I'm using drawImage
to draw the images on the canvas, but when I use the following code:
var canvas = document.getElementById("canvas");
window.open(canvas.toDataURL("image/png"));
It doesn't show the drawn images on the DataUrl
images.
How can I make sure that the images that are drawn on the canvas are also visible in the image given by toDataURL
?
Upvotes: 0
Views: 320
Reputation: 6371
What are the URLs of your page and the images you are drawing?
If your images are not coming from the same origin as the page, you will not be able to use toDataURL
or any other methods to read the contents of the canvas; this is an intentional security feature. Check your JavaScript error console and you may see something like "DOM ERROR" or "SECURITY EXCEPTION".
What do I mean? I mean that if your page is at some URL (e.g., test.com
, localhost:8080
, file:///home/foo/
) and the images you are drawing are located at URLs with different origins (google.com
is a different origin from test.com
, localhost:3000
is a different origin from localhost:8080
, some browsers treat file:///
urls as if they are always from a different origin) then the browser will mark your canvas as unreadable once you draw the image to it.
Why is it this way? Pages can display images from other origins, but many other forms of cross-origin access are denied unless explicitly granted-- XMLHttpRequest
s, for example.
file
URLs are treated differently as well because they are potentially more abusable. If you are using local files for the page and images, serve them with a trivial web server instead.
The first bullet in this section applies.
Upvotes: 1