toDataURL 抛出未捕获的安全异常 [英] toDataURL throw Uncaught Security exception

查看:25
本文介绍了toDataURL 抛出未捕获的安全异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两套用于测试 html5 canvas 的代码

I have two Set of Code for testing html5 canvas

设置 1 - 完美运行

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());

设置 2 - 显示异常错误(未捕获的安全错误:无法在HTMLCanvasElement"上执行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,/, "")); 
}

我不知道为什么在 Set 1 toDataURL 中没有抛出任何异常,其中 Set toDataURL 将抛出异常并且两者都使用相同的图像集.不同之处在于第一组我用 HTML 硬编码画布,第二组我通过 javascript 创建它.

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.

我对 Set 2 代码的目标是获得图像的 64 基本编码.

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

推荐答案

这是一个 CORS 问题 - Gravatar 发送了正确的标题,您只需要将正确的属性放入:

This is a CORS issue - Gravatar sends the correct headers, you just need to put the correct attribute in:

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

function getBase64() {
    var 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");
    alert(dataURL.replace(/^data:image/(png|jpg);base64,/, "")); 
}
getBase64();

请注意,您的第一个示例在我测试时也失败了,正如它应该的那样.

Note that your first example also failed when I tested it, just as it should.

这篇关于toDataURL 抛出未捕获的安全异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆