1

我正在使用 html-to-image 库将 div 元素转换为图像,这对于单个 div 工作正常,但是如果我将它用于 for 循环中的 div 则它会中断

    <div *ngFor="let template of templates; index as i">
      <div id="{{template.templateName}}_front_{{i}}" [innerHTML]="(template.templateHtmlFront) | safeHtml">
      </div>
      <div id="{{template.templateName}}_back_{{i}}"
        [innerHTML]="(template.templateHtmlBack) | safeHtml"></div>
    </div>

我想转换图像中的每个正面和背面模板。所以我在 ts 文件中编写了以下代码

async createFiles() {
const imageData: any[] = [];
for (let tempIdx = 0; tempIdx < this.templates.length; tempIdx++) {
 
  const containerFront = document.getElementById(`${template.templateName}_front_${tempIdx}`);
 
  //save front template
  if (containerFront) {
    await htmlToImage.toJpeg(containerFront)
      .then((dataUrl) => {
        const imageName = `${template.templateId}_front.jpeg`;
        const imageBlob: Blob = this.service.dataURItoBlob(dataUrl);
        const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' });
        imageData.push(imageFile);
      }).catch(function (error) {
        console.error('oops, something went wrong!', error);
      });
  }
  //Save back
    const containerBack = document.getElementById(`${template.templateName}_back_${tempIdx}`);
    if (containerBack) {
      await htmlToImage.toJpeg(containerBack)
        .then((dataUrl) => {
          const imageName = `${template.templateId}_back.jpeg`;
          const imageBlob: Blob = this.service.dataURItoBlob(dataUrl);
          const imageFile = new File([imageBlob], imageName, { type: 'image/jpeg' });
          imageData.push(imgFile);              
        }).catch(function (error) {
          console.error('oops, something went wrong!', error);
        });
    }
  }


}

}

这适用于最多 10 到 15 条记录,但模板大小超过 15 则应用程序挂起(或崩溃)。对于 10-15 条记录也需要 15 分钟(这很慢)有没有更好的方法让它工作?

4

0 回答 0