Hướng dẫn html2canvas async example - ví dụ không đồng bộ html2canvas

Tôi có một vấn đề trong đó tôi cần chạy 2 phương thức theo một thứ tự cụ thể, chờ phương pháp đầu tiên hoàn thành trước khi chạy phương thức thứ hai.

Dưới đây là 2 phương pháp mẫu sau:

part1() {
  const element = document.getElementById("capture") as HTMLCanvasElement;
  html2canvas(element).then((canvas) => {
    this.thecanvas = canvas.toDataURL();
    console.log('Dont do part2 until the.thecanvas is populated');
  });
}


part2() {
  // do other stuff but only after part1 is completed
  console.log('All completed');
}

Tôi đang chạy chúng như thế này:

main() {
    // I need them to run in this sequence
    this.part(); // first
    this.part2(); // last
}

Tôi đoán tôi nên sử dụng async/await?

Làm thế nào để tôi làm điều này trong Angular 12?

Hướng dẫn html2canvas async example - ví dụ không đồng bộ html2canvas

Hỏi ngày 24 tháng 10 năm 2021 lúc 19:33Oct 24, 2021 at 19:33

Có, bạn có thể sử dụng async/await. Đây là cách bạn thay đổi mã của mình:

part1() {
  const element = document.getElementById("capture") as HTMLCanvasElement;

  return new Promise(async (resolve, reject) => {
      try {
        const canvas  = await html2canvas(element)
        this.thecanvas = canvas.toDataURL();
        console.log('Dont do part2 until the.thecanvas is populated');
        // when you complete the things successfully, you shoule call resolve else call reject
        resolve('Dont do part2 until the.thecanvas is populated'); 
      } catch (error) {
        reject(error);
      }
      
  })
 
}

part2() {
  // do other stuff but only after part1 is completed

  return new Promise((resolve, reject) => {
      console.log('All completed'); 
      // when you complete the things successfully, you shoule call resolve else call reject
      resolve('All completed');
  })
  
}

Bạn luôn có thể làm theo các bước này khi bạn có một cái gì đó trong tự nhiên. Bạn có thể tạo ra một lời hứa và bạn có thể resolve/reject dựa trên kết quả.

Đã trả lời ngày 25 tháng 10 năm 2021 lúc 6:38Oct 25, 2021 at 6:38

Apoorva Chikaraapoorva ChikaraApoorva Chikara

7.7893 huy hiệu vàng20 Huy hiệu bạc33 Huy hiệu đồng3 gold badges20 silver badges33 bronze badges

Tôi có nhiệm vụ xuất 9 biểu đồ được hiển thị trong 9 bộ phận riêng biệt, để xuất tất cả các biểu đồ tôi đã sử dụng hàm HTML2Canvas, tôi muốn xuất mỗi biểu đồ trong mỗi tờ PDF với kích thước A4 bên dưới là logic của tôi để trích xuất tất cả 9 biểu đồ chỉ bằng một cú nhấp chuột , Tôi đang sử dụng khung Angular 2 (nay là 6).
To export all charts i used html2canvas function, i wanted to export each graph in each pdf sheets with a4 size
below is my logic to extract all 9 charts on one click,
I am using angular 2(now 6) framework.

  • Khi nhấp vào chức năng generateAllPdf() thực thi,
  • Tôi sẽ thu thập tất cả 9 id's từ bộ sưu tập HTML của tôi,
  • lặp qua từng chức năng ____10 và gọi
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    1,
  • Khi
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    1 chạy trong nền để xử lý hình ảnh, tôi sử dụng
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    3 trên chức năng,
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    3 on function,
  • Sau khi
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    1 hoàn thành quy trình của mình, tôi sẽ lưu tài liệu,
    document,
  • Nếu giả sử tôi sẽ không sử dụng
    main() {
        // I need them to run in this sequence
        this.part(); // first
        this.part2(); // last
    }
    
    3 Tôi sẽ tải xuống một trang trống.
    page.

Dưới đây là logic mã của tôi,

// As All Functions in js are asynchronus, to use await i am using async here
 async generateAllPdf() {
    const doc = new jsPDF('p', 'mm', 'a4');
    const options = {
      pagesplit: true
    };
    const ids = document.querySelectorAll('[id]');
    const length = ids.length;
    for (let i = 0; i < length; i++) {
      const chart = document.getElementById(ids[i].id);
      // excute this function then exit loop
      await html2canvas(chart, { scale: 1 }).then(function (canvas) { 
        doc.addImage(canvas.toDataURL('image/png'), 'JPEG', 10, 50, 200, 150);
        if (i < (length - 1)) {
          doc.addPage();
        }
      });
    }
    // download the pdf with all charts
    doc.save('All_charts_' + Date.now() + '.pdf');
  }

Tôi cũng có cùng một ý tưởng. Nhưng tôi đã sử dụng foreach thay vì cho vòng lặp. Như thế này: `TypeScript
` typescript

    elements.forEach(async (el, index) => {
      const canvasCreated = await html2canvas(el, this.canvasOptions);
      const image = this.convertCanvasToImage(canvasCreated);
      this.add_Image_to_PDF(pdf, image);
      if (index === ( elements.length -1)) resolve("resolved");
    });

`Nhưng thật thú vị, Foreach dường như không chờ đợi HTML2Canvas. Không chắc chắn nếu hành vi mong đợi của nó. Vì vậy, tôi cũng chuyển sang Loop dường như đang hoạt động.
But interestingly, forEach does not seems to wait for html2canvas. Not sure if its the expected behaviour. So i also switched to for loop which seems to be working.