javascript - 将base64图像数据输出到新窗口而不被阻止?

标签 javascript jquery base64

现在有一点 Javascript 噩梦。

我使用 html2canvas 将 div 转换为 Canvas ,然后使用 .toDataURL 将 Canvas 转换为 Base64 数据流。

我想在新窗口中打开 Base64 图像数据,但它被我测试过的每个弹出窗口阻止程序阻止。

这是我的函数的示例

function generateImage(xarg){
    var divid= document.getElementById(xarg);
    html2canvas(divid, {
        onrendered: function(canvas) {
            var imgdata = canvas.toDataURL("image/png");
            window.open(imgdata);
        }
    });
}

知道为什么我的 window.open 被阻止吗?

编辑:我的另一个想法是启动图像的下载,但是我找到的每个解决方案都需要将数据更改为image/octet-stream,这会弄乱文件类型,我的用户将无法处理这个问题(尤其是移动设备上的用户)。 我原本有一篇更长的文章来解释我的情况,但为了简洁起见我将其 chop 。

最佳答案

有关弹出窗口由于异步打开方式而被阻止的其他直接响应(甚至来自单击事件的回调)。我通过以下方式解决了这个问题: - 直接在点击处理程序上打开一个空白弹出窗口 - 启动 html 内容的“canva-ification” - 创建一个临时表单,在弹出窗口中发布 Canva Base64 数据

这种方法的缺点是在生成 Canvas 时用户会看到一个空白的弹出窗口。我希望这会有所帮助。

function clickHandler(elementId /*the id of the element to convert to an image */) {
    // opens the popup directly -> not blocked by browsers
    var popup = window.open('about:blank', 'screenshotWindow', 'width=950,height=635');

    // creates the form
    var form = window.document.createElement('form');
    form.setAttribute('method', 'post');
    form.setAttribute('target', 'screenshotWindow');
    window.document.body.appendChild(form);

    html2canvas(window.document.getElementById(elementId), {
        onrendered: function(canvas) {
            // posts the base64 content in the popup with the form and removes it
            form.setAttribute('action', canvas.toDataURL('image/png'));
            popup.focus();
            form.submit();
            window.document.body.removeChild(form);
        }
    });
}

关于javascript - 将base64图像数据输出到新窗口而不被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16206973/

相关文章:

java - 解码 Base64 字符串时出错

css - 有没有办法在悬停时仅使用 css 制作 base64 编码的背景图像 png 黑白?

javascript - body 不会在溢出时滚动

javascript - 如何在 Angular 8 中正确使用 setValue

javascript - 如何删除焦点上的占位符

javascript - jQuery从左到右动画定位问题

javascript - IE11 HTTPS AJAX XMLHttpRequest : Network Error 0x2eff, 由于错误 00002eff,无法完成操作

javascript - 使用 jQuery 更改 html 的主体

javascript - 屏幕中间的中心图像 + 覆盖

c - 我如何在 C 程序中对 SHA1() 字符串进行 base64 编码