canvas.toDataURL()和drawImage()的安全性错误

mar*_*tin 5 javascript firefox google-chrome html5-canvas

<!doctype html>
<canvas id="canvas" height="200" width="200"></canvas>
<div id="new"></div>
<script>
var div = document.getElementById("new");
var canvas = document.getElementById("canvas");  
var ctx = canvas.getContext("2d");  
var img = new Image();

img.src = 'http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png';
//img.src = 'local.png';

img.onload = function(){
    //draws the image on the canvas (works)
    ctx.drawImage(img,0,0,200,200);

    //creates an image from the canvas (works only for local.png)
    var sourceStr = canvas.toDataURL();

    //creates the img-tag and adds it to the div-container
    var newImage = document.createElement("img");
    newImage.src = sourceStr;
    div.appendChild(newImage);
}
</script>
Run Code Online (Sandbox Code Playgroud)

此脚本使用html5徽标创建画布.从这个画布我想使用"toDataURL()" - 方法创建一个图像.在这里我收到一个安全错误.

Firefox说 - 错误:未捕获异常:[例外..."安全错误"代码:"1000"nsresult:"0x805303e8(NS_ERROR_DOM_SECURITY_ERR)"

Chrome说 - 未捕获错误:SECURITY_ERR:DOM例外18

如果我在服务器上使用带有图像的脚本,它可以正常工作.所以它认为这次它真的是一个功能,而不是一个bug.有没有人知道我如何使用画布创建一个图像与另一个服务器的图像?顺便说一句:如果您将站点作为没有Web服务器的本地文件运行,则会发生错误.

cop*_*opy 7

你是对的,这是一个安全功能,而不是一个bug.

如果阅读图像(例如用toDataURLgetImageData)可以工作,你也可以https://mail.google.com/mail/从访问者的上下文中读取他的电子邮件或其他什么.

因此,canvas元素具有origin-clean标志,该标志在外部图像写入画布时设置.在这种情况下,您再也无法从中读取.

你可以阅读更多有关此主题在这里.


Rya*_*yan 0

我认为该错误是同源策略的扩展,基本上它不允许您操纵来自另一台服务器的资源。尽管不安全,您可以在服务器中构建一种检索外部资源的方法:myserver.com/?external=url/path/to/img... 理论上可行。