Within my angular 11 component, I have a process that iterates through elements on a page and converts them from HTML to canvas to images, which are then appended to a form. The problem I am encountering is that the promise always resolves after the 'done' message is logged to the console. How can I ensure that all instances of the 'generateCanvasFromHtml' function complete before continuing with the script following the loops? Despite this sequencing issue, the functionality of the function itself works as intended.
generateImagesFromPlan(): void {
this.imageGenerating = true;
// Create an empty FormData object for the images to be submitted
const formData = new FormData();
// Retrieve all sections available on the plan
const pdfSections = document.querySelectorAll('[data-pdfsection]');
for (let section of pdfSections as NodeListOf<HTMLElement>) {
const sectionNumber = section.dataset.pdfsection;
console.log('sectionName', sectionNumber)
const pdfComponents = section.querySelectorAll('[data-component]');
console.log('pdfComponents', pdfComponents)
for (let element of pdfComponents as NodeListOf<HTMLElement>) {
const componentImageNumber = element.dataset.component;
console.log('componentName', componentImageNumber)
this.generateCanvasFromHtml(element).then(canvas => {
canvas.toBlob((blob) => {
formData.append(sectionNumber, blob, componentImageNumber + '.png');
console.log('blob added');
}, 'image/png');
});
}
}
for (let pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
console.log('done');
this.imageGenerating = true;
}
generateCanvasFromHtml(elem: HTMLElement): Promise<HTMLCanvasElement> {
const clone = elem.cloneNode(true);
const targetWidth = 1200;
const iframe = document.createElement('iframe');
iframe.style.visibility = 'hidden';
iframe.width = targetWidth + 'px';
iframe.height = '0px';
document.body.appendChild(iframe);
const iframeDocument = iframe.contentDocument;
iframeDocument.replaceChild(clone, iframeDocument.documentElement);
const targetHeight = iframeDocument.documentElement.scrollHeight;
iframe.height = targetHeight + 'px';
console.log('targetHeight=' + targetHeight);
document.body.removeChild(iframe);
const options = {
width: targetWidth,
windowWidth: targetWidth,
height: targetHeight
};
return html2canvas(elem, options);
}