我有一个捕获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();
});
}