Managing two distinct functions, where one converts images from any format to canvas and then to WEBP image format, while the other logs the converted image. I am encountering an issue where the result of the image is undefined when logged in the saveToBackend
function. However, when I log the converted image within the convertImage
function, it displays correctly. How can this problem be resolved?
Displayed below are the functions utilized in my NUXT app:
convertImage(file) {
// Image conversion process
let src = URL.createObjectURL(file)
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d')
let userImage = new Image();
userImage.src = src
userImage.onload = function() {
canvas.width = userImage.width;
canvas.height = userImage.height;
ctx.drawImage(userImage, 0, 0);
let webpImage = canvas.toDataURL("image/webp");
console.log(webpImage); // Image displayed correctly in console
return webpImage
}
},
async saveToBackend(file, result) {
// Image conversion to webp format
let webpFile = await this.convertImage(file)
console.log(webpFile); // Displays 'undefined' in the console
}