I have this function that converts an image URL to a base64 image string. The thing is that the function needs a callback, and I use a console.log to print the string (which works), but I need the string to be saved in a variable. Here is the code:
function convertImageToBase64(imgUrl, callback) {
const image = new Image();
image.crossOrigin = 'anonymous';
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.height = image.naturalHeight;
canvas.width = image.naturalWidth;
ctx.drawImage(image, 0, 0);
const dataUrl = canvas.toDataURL();
callback && callback(dataUrl);
}
image.src = imgUrl;
}
And here's how I call the function:
convertImageToBase64(imgEmpresa, console.log);
convertImageToBase64(imgPropia, console.log);
Both img variables are URL strings I obtain through other methods. It works perfectly fine, and the output of the console.log is the base64 string. But the thing is that I need that variable to be stored somewhere and I have literally no clue on how to do it.
I tried making a function to serve as callback that just returns the variable, but that doesn't work