canvas.toDataURL() causing a security error

2019-04-29 21:38发布

问题:

I'm using HTML5 canvas and the .toDataURL() function through KineticJS's .toDataURL() method. The canvas uses images that my users uploaded to the site, which are stored on a different machine and subdomain farm1.domain.com.

Problem: When .toDataURL() is called, I get the error

SECURITY_ERR: DOM Exception 18 

Is there a way around this? I also get the same problem if the user access the page via domain.com and the image is hosted at www.domain.com.

Attempt:

I added the following lines to httpd.conf within virtualhost and restarted the apache service.

Header add Access-Control-Allow-Origin "http://www.domain.com"
Header add Access-Control-Allow-Origin "http://domain.com"
Header add Access-Control-Allow-Origin "http://farm1.domain.com"

I still get the same error when accessing image hosted on www.domain.com from page on domain.com! Is there a way around this in KineticJS?

回答1:

You will need to add the Access-Control-Allow-Origin headers to the images you are loading, not to the page which is loading them. For details on this header, and on CORS in general, you may want to read "CORS isn't just for XHR", which specifically discusses this issue.



回答2:

There is no way around this error. Images loaded in a canvas from a different domain will raise this error as currently implemented by every browser. In your case the images should be stored in the same domain and you would not be getting exceptions.