Tengo un método que captura un div. Llamo a este método llamado capture() desde otro método.
Aquí está el código:
theimage; // define the variable callcapture() { // do stuff this.capture(); // Call the method here // Do other stuff below BUT (Do not run the rest of the code until "this.capture() has finished ") } capture() { const element = document.getElementById("capture") as HTMLCanvasElement; html2canvas(element).then((canvas) => { this.theimage = canvas.toDataURL(); }); }¿Cómo puedo hacer esto?
¿Qué tal usar @viewChild de Angular para eso? Rara vez es una buena idea usar métodos JS nativos como getElementById , getElementsByClassName , etc. en una aplicación Angular.
<canvas #myCanvas></canvas> @ViewChild('myCanvas', {static: false}) canvasElem: ElementRef;Y luego trabajas con eso:
const context = this.canvasElem.nativeElement.getContext("2d"); const base64:string = this.canvasElem.nativeElement.toDataURL();Puede devolver la promesa y usar otra then asegurarse de que el elemento ya se haya capturado :
callcapture() { // do stuff this.capture().then(() => { // Do other stuff below BUT (Do not run the rest of the code until "this.capture() has finished ") }); } capture() { const element = document.getElementById("capture") as HTMLCanvasElement; return html2canvas(element).then((canvas) => { this.theimage = canvas.toDataURL(); }); }