Angular调用函数来捕获div,并在继续之前等待捕获



我有一个捕获div的方法。我从另一个方法调用这个方法称为capture()。

代码如下:

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();
});
}

我该怎么做?

使用Angular的@viewChild如何?使用原生JS方法,如getElementById,getElementsByClassName等,很少是一个好主意;

<canvas #myCanvas></canvas>
@ViewChild('myCanvas', {static: false}) canvasElem: ElementRef;

然后你用它:

const context = this.canvasElem.nativeElement.getContext("2d");
const base64:string = this.canvasElem.nativeElement.toDataURL();

您可以返回承诺并使用另一个then来确保元素已被捕获:

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();
});
}

相关内容

  • 没有找到相关文章

最新更新