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

<!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>

此脚本创建一个带有 html5-logo 的画布.在这个画布上,我想使用toDataURL()"方法创建一个图像.在这里我得到一个安全错误.

This script creates a canvas with the html5-logo. From this canvas I want to create an image, using the "toDataURL()"-method. Here I get a security error.

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

Firefox says - Error: uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)"

Chrome 说 - 未捕获的错误:SECURITY_ERR: DOM Exception 18

Chrome says - Uncaught Error: SECURITY_ERR: DOM Exception 18

如果我在服务器上使用带有图像的脚本,它可以正常工作.所以它认为这一次它真的是一个特性而不是一个错误.有谁知道我如何使用画布创建图像而无需其他服务器的图像?顺便说一句:如果您在没有网络服务器的情况下将站点作为本地文件运行,则会发生错误.

If I use the script with an image on the server it works fine. So it think this time it is really a feature and not a bug. Does anyone has an idea how I can create an image using canvas with out of an image form an other server? BTW: the error occurs if you run the site as a local file without a webserver.

推荐答案

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

You are right, this is a security feature, not a bug.

如果读取图片(例如使用 toDataURLgetImageData)可行,您也可以读取 https://mail.google.com/mail/ 从访问者的上下文中获取他的电子邮件或其他内容.

If reading the Image (for instance with toDataURL or getImageData) would work, you could also read https://mail.google.com/mail/ from the context of your visitor get his emails or whatever.

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

Therefore, canvas elements have a origin-clean flag, which is set when external images are written to the canvas. In that case, you can no longer read from it.

您可以阅读有关此主题的更多信息 这里.

You can read more about this topic here.

相关文章