Search code examples
javascriptcanvashtml5-canvasbase64jcrop

jCrop HTML5 Canvas Base64


I'm trying to work with jCrop and canvas.

Instead of sending the image to the server and back again with a cropped image, I'm trying to crop it directly, using canvas, because with the result, I transform the crop in a base64 image and send to the server.

I have an example JSFiddle.

I crop the image then convert in canvas but I cant transform image in base64. The below error appears:

"SecurityError: The operation is insecure."

I have tried with..

console.log(canvas.toDataURL());

What am I doing wrong?


Solution

  • In general, this problem is due to CORS (cross-origin resource sharing) requirements not being fulfilled.

    To avoid this you can either:

    • Serve the image being cropped from the same origin as the page
    • Request cross-origin use by supplying crossOrigin property to the image
    • Use a proxy to serve the image from the external site through your server (in which case much of the point is lost doing everything locally).

    In addition:

    • When testing, don't use the local file:// protocol but a light local server (ie. Mongoose)

    If not you will get an security error every time you use toDataURL (or getImageData).

    About requesting CORS usage from external servers: you can only request such use but it's up to the server to grant the permission or not.

    To request either:

    <img src="..." crossOrigin="anonymous" >
    

    or from JavaScript:

    var img = new Image;
    
    img.onload = handleOnLoad;
    img.crossOrigin = 'anonymous';
    img.src = '...';
    

    If denied the image won't load at all.