javascript - 在javascript中下载canvas时出现"Not allowed to navigate top frame to data URL"

标签 javascript download html5-canvas

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

我看过有关此问题的其他帖子,他们通常试图展示他们的 Canvas 或其他东西,而不是保存 Canvas 。

这是我的代码:

//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>

我想要发生的是保存 Canvas 。

最佳答案

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

关于javascript - 在javascript中下载canvas时出现"Not allowed to navigate top frame to data URL",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066345/

相关文章:

javascript - 我想禁用 Firefox 和 IE 中的右键单击选项

javascript - 根据数据库中的下拉值设置 td 填充的背景颜色

Android:下载大文件

css - 无法将伪元素添加到 Canvas ?

JavaScript:一张 Canvas 多个纹理

javascript - 从当前位置开始的 jquery 动画

javascript - 访问 Jquery 对象 [] 并得到错误

objective-c - ASIHttp 同步请求在返回后运行委托(delegate)方法

java - 如何以西里尔文返回下载的文件名?

javascript - 阻止动态 JS 阶段右键单击中的默认上下文菜单?