Search code examples
javascripthtmlimagecanvasjcrop

crop canvas html5 to image as base64 on client side without server-side code


I have an image source like http://socialtalent.co/wp-content/uploads/blog-content/so-logo.png and no FileReader object.

I need to crop this image from different domain using client-side JavaScript only.

When I am trying to get source from canvas (canvas.toDataURL()) I get a Security Error (unsecure operation).

In summary:

  1. Is there a way to avoid this error? If I need to use CORS (crossOrigin) for the server/client then please provide example on the server-side settings;

  2. Is there any hack to prevent this error?

  3. Is it possible to combine 3 operations (crop, rotate, zoom) on canvas and then get a source of image as Base64?

  4. It would be great to have a working example.

Thank you.


Solution

    1. Not any more. (Link to enabling CORS on server: http://enable-cors.org/)

    2. Not any more.

    3. Yes.

    4. Annotated code example: http://jsfiddle.net/m1erickson/gz6e8/

    Once you have properly configured your server for CORS you can download an image that won't taint your canvas like this:

    var img=new Image();
    img.crossOrigin="anonymous";
    img.src="http://yourConfiguredServer.com/logo.png";
    

    Illustration of the results:

    enter image description here