acornejo / jquery-cropbox

jQuery Cropbox plugin
http://acornejo.github.io/jquery-cropbox/
MIT License
345 stars 82 forks source link

Failed to execute 'toDataURL' #73

Closed ncubica closed 9 years ago

ncubica commented 9 years ago

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Hi, if you are using an image that had been uploaded from a different server than yours, you get this error. http://stackoverflow.com/questions/22710627/tainted-canvases-may-not-be-exported

So to solve I had to add the follow header which obviously is not refer to this specific plugin. <?php header('Access-Control-Allow-Origin: *'); ?>

But also I had to add this code to the pluging

            getDataURL: function () {
                if(!supportsCanvas) {
                    // return an empty string for browsers that don't support canvas.
                    // this allows it to fail gracefully.
                    return false;
                }

                var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d');

                var img = new Image();
                img.setAttribute('crossOrigin', 'anonymous');
                img.src = this.$image.url;

                canvas.width = this.options.width;
                canvas.height = this.options.height;
                ctx.drawImage(img, this.result.cropX, this.result.cropY, this.result.cropW, this.result.cropH, 0, 0, this.options.width, this.options.height);
                return canvas.toDataURL();
            },

instead of sending this.$image.get(0) I created a new image with setAttribue img.setAttribue('crossOrigin','anonymous'); https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

which worked.

I don't know if this can be a bug but I let it here if somebody else found this as problem.