SecurityError:在画布中加载图像,修改它并创建dataURL [英] SecurityError: Load an image in canvas, modify it and create dataURL

查看:100
本文介绍了SecurityError:在画布中加载图像,修改它并创建dataURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to use HTML5 to bring in an image file, draw it to the canvas, do some manipulation of it, then return the dataURL so that I can reference this newly generated image.

以下是图像加载代码的简单示例:

Here's a quick example of what the image loading code looks like:

<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:操作不安全

So, with the code like that the log of c.toDataURL() is a blank canvas, presumably because the log() call is executed before the draw() function finishes. If instead, I move that log call inside draw() I get a JavaScript error: SecurityError: The operation is insecure

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

If instead, I use the local image and put the log in to the draw function, I get the expected output there - but still blank canvas outside the function

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

I guess my actual question is: how can load in an external image to a canvas, and then modify it's contents in some fashion?

推荐答案

需要在服务器托管上设置交叉原点如果你想做任何形象的图像,使其成为支持CORS的图像修改。

Cross origin needs to be set on the server hosting the image making it a CORS enabled image if you want to do any sort of image modification.

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

If this is not set on the server side the only other option is to download the image via a server side proxy on the same domain as your script. As long as the image is coming from the same domain you'll be able to modify it.

这篇关于SecurityError:在画布中加载图像,修改它并创建dataURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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