我正在编写一个函数来使用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 关键字后,它在不同浏览器中的行为异常。
这里使用单独的 div 来显示所有内容,例如:
<div id="name" style="top:103px;left:83px">name</div>
<div id="dob" style="top:200px;left:83px">dob</div>