I'm developing a certificate designing application, and I want to send a base64 datUrl of the certificate to the backend. I wrote a "getThumbnail()" function in order to return a compressed base64 dataUrl of the certificate for preview.
getThumbnail(): string {
let node: any = document.getElementById('certificate-preview-container');
let thumbnail: string = "";
htmlToImage.toPng(node).then(function (dataUrl) {
let img = new Image();
img.src = dataUrl;
document.body.appendChild(img);
// console.log("DataUrl: ", dataUrl);
console.log("DataUrl: ", typeof(dataUrl));
//return dataUrl;
img.onload = function() {
// Create a canvas and draw the compressed image
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Set the canvas dimensions to the desired size (e.g., for compression)
canvas.width = img.width * 0.2; // Adjust the width as needed
canvas.height = img.height * 0.2; // Adjust the height as needed
// Draw the image onto the canvas
ctx!.drawImage(img, 0, 0, canvas.width, canvas.height);
// Get the compressed data URL from the canvas
const compressedDataURL = canvas.toDataURL('image/png', 0.5); // Adjust quality as needed
// Display the compressed image
const compressedImage = new Image();
compressedImage.src = compressedDataURL;
thumbnail = compressedDataURL;
console.log("Thumbnail: ", typeof(thumbnail));
//return thumbnail;
document.body.appendChild(compressedImage);
console.log("Compressed image: ", compressedDataURL);
return thumbnail;
}
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
//return thumbnail;
});
return thumbnail;
}
Then I wrote a "saveCertificate()" function which sends the required data as payload to the backend, which also includes the "thumbnail" field which is supposed to get the compressed base64 dataUrl.
saveCertificate(){
let data : CertificatePostBody = {
certificate : {
"id": Number(this.certificateId),
"certificateTemplate": this.certificate.template,
"height": this.certificate.height,
"width": this.certificate.width,
"backgroundImage": this.certificate.backgroundImage,
"orientation": this.certificate.orientation,
"certificateType": this.certificate.certificateType,
"certificateName" : this.certificate.certificateName,
"dateFormat" : this.certificate.date_format,
"thumbnail" : this.getThumbnail()
//"thumbnail": "test2"
}
};
this.certificateService.updateCertificate(data).subscribe((res:any)=>{
console.log('res=>', res);
})
The problem is that the "thumbnail" field shows blank when I check it in the network tab in inspect element, meaning the getThumbnail() function is returning a blank string. Now I am aware it could be because of the asynchronous nature of the htmlToImage.toPng function and it returns a promise. How can I modify the getThumbnail() function so that it returns the compressed dataUrl as string for me to send it to backend?