Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - toDataURL throw Uncaught Security exception

I have two Set of Code for testing html5 canvas

Set 1 - Work perfectly

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas"/>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Set 2 - Show exception error (Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported. )

<img id="preview1" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">

function getBase64() {
    var img = new Image();
    img =  document.getElementById("preview1");
    var canvas = document.createElement("canvas");
    canvas.width =img.width;
    canvas.height =img.width;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png"); //This line of code will throw exception
    alert(  dataURL.replace(/^data:image/(png|jpg);base64,/, "")); 
}

I have no idea why in Set 1 toDataURL is not throwing any exception where Set toDataURL will throw exception and both are using same set of image.The different is in the first set i hardcode the canvas in HTML , and second set i create it through javascript.

My objective for Set 2 code is to get 64 base encode of the image.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can just use crossOrigin Attribute.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...