我想保存我的画布到img。我有这样一个函数:

function save() {
    document.getElementById("canvasimg").style.border = "2px solid";
    var dataURL = canvas.toDataURL();
    document.getElementById("canvasimg").src = dataURL;
    document.getElementById("canvasimg").style.display = "inline";
}

它给出了错误:

Uncaught SecurityError:未能在“HTMLCanvasElement”上执行“toDataURL”:受污染的画布可能无法导出。

我该怎么办?


当前回答

出于安全原因,您的本地驱动器被声明为“other-domain”,并将污染画布。

(这是因为你最敏感的信息可能在你的本地驱动器上!)

在测试时尝试以下变通方法:

Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders). Post your images to a site that supports cross-domain sharing (like dropbox.com or GitHub). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...) Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

其他回答

似乎您正在使用的图像来自一个URL,没有设置正确的访问控制-允许起源头,因此出现了问题。您可以从您的服务器获取该映像,并从您的服务器获取它以避免CORS问题。

出于安全原因,您的本地驱动器被声明为“other-domain”,并将污染画布。

(这是因为你最敏感的信息可能在你的本地驱动器上!)

在测试时尝试以下变通方法:

Put all page related files (.html, .jpg, .js, .css, etc) on your desktop (not in sub-folders). Post your images to a site that supports cross-domain sharing (like dropbox.com or GitHub). Be sure you put your images in dropbox's public folder and also set the cross origin flag when downloading the image (var img=new Image(); img.crossOrigin="anonymous" ...) Install a webserver on your development computer (IIS and PHP web servers both have free editions that work nicely on a local computer).

在img标签中将crossorigin设置为Anonymous。

<img crossorigin="anonymous" />

我使用useCORS: true选项解决了这个问题

 html2canvas(document.getElementsByClassName("droppable-area")[0], { useCORS:true}).then(function (canvas){
        var imgBase64 = canvas.toDataURL();
        // console.log("imgBase64:", imgBase64);
        var imgURL = "data:image/" + imgBase64;
        var triggerDownload = $("<a>").attr("href", imgURL).attr("download", "layout_"+new Date().getTime()+".jpeg").appendTo("body");
        triggerDownload[0].click();
        triggerDownload.remove();
    });

这个可以在laravel中顺利工作。

首先,您需要将受污染的画布转换为blob。在此之后,您可以上传一个blob来服务并将其保存为图像。在ajax调用中返回图像URL。

这是一个上传画布blob的ajax调用。

$("#downloadCollage").click(function(){
  canvas.toBlob(function(blob){

    var formDataToUpload = new FormData();
    formDataToUpload.append("_token", "{{ csrf_token() }}");
    formDataToUpload.append("image",  blob);

    $.ajax({
        url:"{{ route('selfie_collage_upload') }}",
        data: formDataToUpload,
        type:"POST",
        contentType:false,
        processData:false,
        cache:false,
        dataType:"json",
        error:function(err){
            console.error(err);
        },
        success:function(data){
            window.location.href= data.url;
        },
        complete:function(){
        }
    });
  },'image/png');
  link.click();
});