首页 > 解决方案 > 在javascript中下载画布时“不允许将顶部框架导航到数据URL”

问题描述

在我的网站上,我正在尝试下载我创建的受污染的画布。当我尝试执行此操作时,我得到“不允许将顶部框架导航到数据 URL:”(后跟一串数据)。

我查看了有关此的其他帖子,他们通常试图展示他们的画布或其他东西,而不是保存画布。

这是我的代码:

//it looks complicated, but the only important lines are the ones before the else statement,
function download_img(el) {
//the if statement is used to see if this is using the canvas or not
    if(document.getElementById("canvasImage").style.display != "none"){
        alert('canvas')
        var canvImg = document.getElementById("canvasImage").toDataURL("image/jpg");
        el.href = canvImg;        
    }else{
//again, this code is for the image side of the project, which works fine
        alert('image')
        var xhr = new XMLHttpRequest();
        xhr.open("GET", document.getElementById("theImg").src, true);
        xhr.responseType = "blob";
        xhr.onload = function(){
            var urlCreator = window.URL || window.webkitURL;
            var imageUrl = urlCreator.createObjectURL(this.response);
            var tag = document.createElement('a');
            tag.href = imageUrl;
            tag.download = "meme";
            document.body.appendChild(tag);
            tag.click();
            document.body.removeChild(tag);
        }
        xhr.send();       
    }
}

我的 HTML:

    <a style="float:left;display:inline;" href="" onclick="download_img(this)">Canvas Button</a>

我想要发生的是画布被保存。

标签: javascriptdownloadhtml5-canvas

解决方案


download属性添加到<a>标签以强制它下载而不是导航。


推荐阅读