SecurityError:在画布中加载图像,修改它并创建dataURL

时间:2012-12-14 16:59:30

标签: javascript html5 canvas

我正在尝试使用HTML5引入图像文件,将其绘制到画布上,对其进行一些操作,然后返回dataURL以便我可以引用这个新生成的图像。

以下是图像加载代码的快速示例:

<canvas id="myCanvas" style="border:1px solid #c3c3c3;">
    Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">
    c = document.getElementById("myCanvas");
    cxt = c.getContext("2d");

    var img=new Image();
    img.src = "http://www.google.com/images/srpr/logo3w.png";
    //img.src = 'image/placemark.png';
    img.onload = function() {
        cxt.drawImage(img, 0, 0);
    }

    console.log(c.toDataURL());
</script>

因此,使用类似的代码,c.toDataURL()的日志是一个空白画布,大概是因为log()调用在draw()函数完成之前执行。相反,如果我在draw()内移动该日志调用,则会收到JavaScript错误:SecurityError: The operation is insecure

如果相反,我使用本地图像并将log放入draw函数,我在那里得到预期的输出 - 但在函数外仍然是空白画布

我想我的实际问题是:如何将外部图像加载到画布中,然后以某种方式修改它的内容?

2 个答案:

答案 0 :(得分:2)

如果您想要进行任何类型的图像修改,需要在托管图像的服务器上设置交叉原点,使其成为CORS enabled image

如果未在服务器端设置此选项,则唯一的其他选项是通过与脚本位于同一域的服务器端代理下载映像。只要图像来自同一个域,您就可以对其进行修改。

答案 1 :(得分:-1)

我的代码没有安全错误:

<pre>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<script src="Scripts/jquery-2.1.0.min.js"></script>

<script type="text/javascript">
    function WindowsLoad()
    {
        var c = document.getElementById("myCanvas");
        var cxt = c.getContext("2d");

        var img = new Image();
        img.src = "http://www.google.com/images/srpr/logo3w.png";
        //img.src = 'image/placemark.png';
        img.onload = function () {
            cxt.drawImage(img, 0, 0);
        }

        console.log(c.toDataURL());
    }   
</script>

<body onload="WindowsLoad();">
    <form id="form1" runat="server">
        <div>
            <canvas id="myCanvas">
            </canvas>
        </div>
    </form>
</body>
</html>
</pre>