简体   繁体   English

canvas.toDataURL() 安全错误

[英]canvas.toDataURL() SecurityError

So I'm using google maps and I get the picture so it looks like this所以我使用谷歌地图,我得到了图片,所以它看起来像这样

<img id="staticMap"
        src="http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=600x300&maptype=roadmap
&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614,-74.012318
&markers=color:red%7Ccolor:red%7Clabel:C%7C40.718217,-73.998284&sensor=false">

I need to save it.我需要保存它。 I have found this:我发现了这个:

function getBase64FromImageUrl(URL) {
    var img = new Image();
    img.src = URL;
    img.onload = function() {

        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));

    };
}

But I get this problem:但我遇到了这个问题:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': tainted canvases may not be exported.未捕获的安全错误:无法在“HTMLCanvasElement”上执行“toDataURL”:可能无法导出受污染的画布。

I searched for fixes.我搜索了修复程序。 I found a sample here How to use CORS but still I can't tie these 2 pieces of code together to make it work.我在这里找到了一个示例如何使用 CORS,但我仍然无法将这两段代码结合在一起以使其工作。 Maybe I'm doing it the wrong way and there is a simpler way to do it?也许我做错了,有更简单的方法吗? I'm trying to save this pic so that I can transfer the data to my server.我正在尝试保存这张图片,以便我可以将数据传输到我的服务器。 So maybe someone did something like this and knows how to make .toDataURL() work as I need it?所以也许有人做了这样的事情并且知道如何让.toDataURL()在我需要的时候工作?

Unless google serves this image with the correct Access-Control-Allow-Origin header, then you wont be able to use their image in canvas.除非谷歌使用正确的Access-Control-Allow-Origin标头提供此图像,否则您将无法在画布中使用他们的图像。 This is due to not having CORS approval.这是由于未获得CORS批准。 You can read more about this here , but it essentially means:你可以在这里阅读更多关于这个的信息,但它本质上意味着:

Although you can use images without CORS approval in your canvas, doing so taints the canvas.尽管您可以在画布中使用未经 CORS 批准的图像,但这样做会污染画布。 Once a canvas has been tainted, you can no longer pull data back out of the canvas.一旦画布被污染,您就无法再从画布中取出数据。 For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods;例如,您不能再使用画布 toBlob()、toDataURL() 或 getImageData() 方法; doing so will throw a security error.这样做会引发安全错误。

This protects users from having private data exposed by using images to pull information from remote web sites without permission.这可以防止用户在未经许可的情况下使用图像从远程网站提取信息而暴露私人数据。

I suggest just passing the URL to your server-side language and using curl to download the image.我建议只将 URL 传递给您的服务器端语言并使用 curl 下载图像。 Be careful to sanitise this though!不过要小心消毒!

EDIT:编辑:

As this answer is still the accepted answer, you should check out @shadyshrif's answer , which is to use:由于此答案仍然是公认的答案,您应该查看@shadyshrif 的答案,该答案是使用:

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This will only work if you have the correct permissions, but will at least allow you to do what you want.在您拥有正确的权限时才有效,但至少可以让您做您想做的事。

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter只需使用crossOrigin属性并将'anonymous'作为第二个参数传递

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.此方法将防止您从您正在访问的服务器收到“访问控制允许来源”错误。

var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;

Try the code below ...试试下面的代码...

<img crossOrigin="anonymous"
     id="imgpicture" 
     fall-back="images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,
                bungalow,high end luxury properties,landed properties,gated guarded house.png" 
     ng-src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" 
     height="220"
     width="200"
     class="watermark">

In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error.就我而言,我使用的是 WebBrowser 控件(强制使用 IE 11),但无法解决错误。 Switching to CefSharp which uses Chrome solved it for me.切换到使用 Chrome 的 CefSharp 为我解决了这个问题。

I had the same error message.我有同样的错误信息。 I had the file in a simple .html, when I passed the file to php in Apache it worked我有一个简单的 .html 文件,当我将文件传递给 Apache 中的 php 时它起作用了

html2canvas(document.querySelector('#toPrint')).then(canvas => {
            let pdf = new jsPDF('p', 'mm', 'a4');
            pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
            pdf.save(filename);
        });

if the picture from the third site didn't set the head of cors,you can never download the picture file through the chrome, even if you use the setAttribute('crossOrigin', 'anonymous');如果第三个站点的图片没有设置cors的头部,则永远无法通过chrome下载图片文件,即使使用setAttribute('crossOrigin', 'anonymous'); Here are some suggestions这里有一些建议

  1. hack the chrome破解铬
  2. write a program to download the picture and then use it with file编写一个程序来下载图片,然后将其与文件一起使用

By using fabric js we can solve this security error issue in IE.通过使用fabric js,我们可以解决IE中的这个安全错误问题。

    function getBase64FromImageUrl(URL) {
        var canvas  = new fabric.Canvas('c');
        var img = new Image();
        img.onload = function() {
            var canvas1 = document.createElement("canvas");
            canvas1.width = this.width;
            canvas1.height = this.height;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(this, 0, 0);
            var dataURL = canvas.toDataURL({format: "png"});
        };
        img.src = URL;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM