In my current project, I am facing a challenge. I am attempting to pass image dataURI as an input from a url link to the image. To achieve this task, I know that I have to utilize canvas and convert it from there. However, since this process involves an 'async' method, I seem unable to generate a proper return value.
getLogo() {
let image = new Image();
let canvas = document.createElement('canvas');
return new Promise((resolve) => {
image.onload = () => {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext('2d').drawImage(image, 0, 0);
let uri = canvas.toDataURL('image/png');
resolve(uri);
};
image.src = this.logo;
});
}
getLogoURI() {
this.getLogo().then((result) => {
console.log(result); // the correct output writes here
return result; // this returns undefined
});
}
To retrieve the URI within a for loop in my class, I make use of this function.
let logo = tariff.getLogoURI();
I suspect that when calling getLogoURI(), it is automatically considered a synchronous function, thus failing to provide the expected outcome. However, I'm unsure about the exact reason behind this behavior.