首页 > 解决方案 > Dom-to-image js库问题

问题描述

我正在编写一个函数来使用dom-to-image将我的dom(带有id内容的div)渲染为png图像并在渲染后上传到我的服务器,因此引入了一个异步函数以等待完成图像处理,但在引入之后,它的在不同的浏览器中呈现异常。 我的渲染图像代码:

function PrintDiv(div, type) {

    return new Promise((resolve) => {
        imgf.src = '';
        var node = document.getElementById(div);
        const scale = 3;
        var options = {
            height: node.offsetHeight * scale,
            width: node.offsetWidth * scale,
            style: {
                transform: "scale(" + scale + ")",
                transformOrigin: "top left",
                width: node.offsetWidth + "px",
                height: node.offsetHeight + "px"
            }
        };
        domtoimage.toPng(node, options).then(function (dataUrl) {
            imgf.src = dataUrl;
            resolve(true);
        }).catch(function (error) {
            console.error('oops, something went wrong!', error);
            resolve(false);
        });
    });
}

驱动代码:

async function savetoserver(){

        if(document.getElementById("sphoto").complete){
        let isImageProcessed=await PrintDiv('content',1);
            if(isImageProcessed){
        // excecute uploading 
            }else{
        //image process failed
        savetoserver();
            }
        }
}

在将函数 savetoserver 更改为 async 之前,它正在处理正确的图像,但在添加 async 关键字后,它在不同浏览器中的行为异常。

预期输出: 在此处输入图像描述

Mozilla Firefox 中的输出: 在此处输入图像描述

在 Chrome 中输出: 在此处输入图像描述

这里使用单独的 div 来显示所有内容,例如:

<div id="name" style="top:103px;left:83px">name</div>
<div id="dob" style="top:200px;left:83px">dob</div>

标签: javascripthtmlcssimage-processingdom-to-image

解决方案


我的问题通过向所有 div 元素添加 css width 属性来解决。

即:我需要名称的最大宽度为 300px,所以我简单地添加了 width=300px,

它看起来像:

<div id="name" style="top:103px;left:83px;width:300px">name</div>

谢谢


推荐阅读