简体   繁体   中英

How can I get images drawn with drawImage to be included when using toDataURL?

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 ?

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 (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM