因为我刚开始是在谷歌浏览器上测试,使用html2canvas 截图的顺序是没有问题的,但是因为现场使用的是火狐浏览器发现截出来的图片顺序不对,排查后发现还是因为异步的问题
更改前
for(let i = 0 ;i<this.wrapperHeight/imgHeight;i++){
new Promise((resolve) => {
setTimeout(resolve, 200); // 每批次截图之间的延时时间,根据实际需求修改
});
opts.y = i*imgHeight
if(i == 0){
opts.height = imgHeight
}else{
opts.height = (i+1)imgHeight-iimgHeight
}
let imgBase = html2canvas(document.getElementById('wrapper'),JSON.parse(JSON.stringify(opts)) ).then(function(canvas) {
return canvas.toDataURL('image/png')
});
console.log(imgBase,i,opts.height,opts.y,"imgBase")
imgBase.then(res=>{
this.svgUrl.push(res)
imgBases.push(res)
})
这个是之前的代码我循环去将一个流程图截成多份
更改后
我们将整个逻辑包装在一个 async
函数 captureImages
中,它会等待每个截图的 Promise 完成,确保按顺序获取图像数据。
async captureImages(){
document.getElementById('wrapper').style.height = this.wrapperHeight+'px';
setTimeout(async ()=>{
let opts = {
scale: 1,
useCORS: true,
allowTaint: true,
// scrollX:0,
// scrollY:0,
// logging: true,
height: document.getElementById('wrapper').scrollHeight,
windowHeight: document.getElementById('wrapper').scrollHeight,
ignoreElements: (item) => {
if (item.classList.contains('save')) {
return true // 排除掉这个元素
}
return false // 保留这个元素
},
y: 0,
};
this.imgBases = []
let imgHeight = this.processFlowDiagramRule.pagingHeight
imgHeight = (this.maxHeight*3+(space+20)*3);
this.svgSize = (this.wrapperHeight)/imgHeight;
this.svgUrl = [];
for(let i = 0 ;i<this.wrapperHeight/imgHeight;i++){
opts.y = i*imgHeight
if(i == 0){
opts.height = imgHeight
}else{
opts.height = (i+1)*imgHeight-i*imgHeight
}
let imgBase =await html2canvas(document.getElementById('wrapper'),JSON.parse(JSON.stringify(opts)) ).then(function(canvas) {
return canvas.toDataURL('image/png')
});
this.imgBases.push(imgBase);
}
console.log(this.imgBases,"this.imgBases")
this.$nextTick(()=>{
this.$emit("dealSvgJson", this.wrapperHeight, this.wrapperWidth,'', this.imgBases);
})
},200);
}
},
//增加流程图分页功能
this.captureImages();
这样截出来的图片顺序就不会有问题啦