简体   繁体   中英

Load image to canvas from 'external' source and save it

What I'm trying to do is to load an image from my server and add it to canvas and then I want to save it.

Add image to canvas. Done When I press save it throws me an error.

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

I searched a little about this error here and on google but I couldn't solve it.

I'm setting crossOrigin to Anonymous as I read I need to do.

var src = "logo.svg";

fabric.util.loadImage(src, function(img) {
    var object = new fabric.Image(img);
    object.set({ 
        left: 0, 
        top: 0
    });
    object.hasRotatingPoint = true;
    object.scaleX = object.scaleY = 1;
    canvas.add(object);
    canvas.renderAll();    
}, null, {crossOrigin: 'Anonymous'});

Then I read that I have to add some rule in .htaccess.

Access-Control-Allow-Origin header

So I created a .htaccess on my domain with the following lines:

<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>

Then I checked if mod_setenvif.c and mod_headers.c are enabled using:

<?php if (strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_headers.c') !== false) {
    echo 'Yes';
}else{
    echo 'No';
} ?>

And for both I get 'Yes'.

Any suggestion would be great.

Thank you

EDIT:

What I'm trying to is to add an image from my server to canvas.

It seems to me that you're not referencing the image correctly in that you'll need a full web URL to access the image. As an example:

var src = "http://www.mywebserver.com/images/logo.svg";

You shouldn't need the cross origin or .htaccess modifications. Your final code should look something like:

var src = "http://www.mywebserver.com/images/logo.svg"

fabric.util.loadImage(src, function(img) {
  var object = new fabric.Image(img);
  object.set({ 
      left: 0, 
      top: 0
  });
  object.hasRotatingPoint = true;
  object.scaleX = object.scaleY = 1;
  canvas.add(object);
  canvas.renderAll();    
}

Set crossOrigin: 'Anonymous' will solve this Tainted canvas issue.

Example:

fabric.util.loadImage('sample.png', function(img) {
 ....
}, null, {crossOrigin: 'Anonymous'});

Refernce: https://github.com/kangax/fabric.js/issues/1386

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM