Why does canvas.toDataURL() throw a security excep

2018-12-31 15:13发布

Did I not get enough sleep or what? This following code

var frame=document.getElementById("viewer");
frame.width=100;
frame.height=100;

var ctx=frame.getContext("2d");
var img=new Image();
img.src="http://www.ansearch.com/images/interface/item/small/image.png"

img.onload=function() {
    // draw image
    ctx.drawImage(img, 0, 0)

    // Here's where the error happens:
    window.open(frame.toDataURL("image/png"));
}

is throwing this error:

SECURITY_ERR: DOM Exception 18

There's no way this shouldn't work! Can anyone explain this, please?

10条回答
低头抚发
2楼-- · 2018-12-31 15:26

You can't put spaces in your ID

Update

My guess is that image is on a different server than where you're executing the script. I was able to duplicate your error when running it on my own page, but it worked fine the moment I used an image hosted on the same domain. So it's security related - put the image on your site. Anyone know why this is the case?

查看更多
几人难应
3楼-- · 2018-12-31 15:27

I had the same problem and all the images are hosted in the same domain... So, if someone is having the same problem, here is how I solved:

I had two buttons: one to generate the canvas and another one to generate the image from the canvas. It only worked for me, and sorry that I don't know why, when I wrote all the code on the first button. So when I click it generate the canvas and the image at the same time...

I always have this security problem when the codes were on different functions... =/

查看更多
谁念西风独自凉
4楼-- · 2018-12-31 15:27

Finally i found the solution. Just need add the crossOrigin as third param in fromURL func

fabric.Image.fromURL(imageUrl, function (image) {
            //your logic
    }, { crossOrigin: "Anonymous" });
查看更多
泪湿衣
5楼-- · 2018-12-31 15:29

I'm using fabric.js and could resolve this by using toDatalessJSON instead of toDataURL:

canvas.toDatalessJSON({ format: 'jpeg' }).objects[0].src

Edit: Nevermind. This results in just the background image being exported to JPG, without the drawing on top so it was not entirely useful after all.

查看更多
临风纵饮
6楼-- · 2018-12-31 15:30

I was able to make it work using this:

Write this on first line of your .htaccess on your source server

Header add Access-Control-Allow-Origin "*"

Then when creating an <img> element, do it as follows:

// jQuery
var img = $('<img src="http://your_server/img.png" crossOrigin="anonymous">')[0]

// or pure
var img = document.createElement('img');
img.src='http://your_server/img.png';
img.setAttribute('crossOrigin','anonymous');
查看更多
梦该遗忘
7楼-- · 2018-12-31 15:32

Seems there is a way to prevent that if image hosting able to provide the following HTTP headers for the image resources and browser supports CORS:

access-control-allow-origin: *
access-control-allow-credentials: true

It is stated here: http://www.w3.org/TR/cors/#use-cases

查看更多
登录 后发表回答