Dinesh
Dinesh

Reputation: 73

Any way to circumvent cross domain image issue in canvas?

When I try to use canvas.toDataURL("image/jpeg"); on image imported from another domain, I get security error. Is there any way around this issue?

Upvotes: 0

Views: 669

Answers (1)

Philipp
Philipp

Reputation: 69663

When you control the server from which you want to load the image, you can modify its cross origin resource sharing (CORS) settings to state your domain as trusted. Refer to the manual of the webserver software it is using and Serverfault for details.

When you don't control the server, a possible workaround is to have your own webserver request the image from the other server and then provide it to the client. Prerequisites for this are:

  1. Some kind of server-sided programming technology (PHP, ASP, JSP, node.js, RoR, Django, Perl or whatever you prefer)
  2. Your server must be authorized to access the image (that's the reason the cross-origin protection exists: Without it websites could leech images they can't access but their visitors can. When a user still has their example.com login cookie set, a javascript on any other website could make them request https://example.com/private/photos/me_naked_01.jpg, draw it to a canvas, get its dataUrl and upload it with an XmlHttpRequest).

Also you should not do this without permission when it means you are requesting the same images from the same server over and over again. The admin will notice the abnormal requests all originating from your webserver and decide to block it.

And when all else fails, you could use the old-school method and allow your users to upload their own images.

Upvotes: 1

Related Questions