Attempting to convert the image into a base64 string using javascript/angularjs code found on this stacko page, for more detailed code you can refer to this link.
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)
The function is called within the controller's initialization, yet the image fails to load at first attempt. However, upon reloading the page or invoking the function again through a button, the image displays properly.
Upon debugging, it appears that only by reaching the last if statement which clears the cache, does the image load successfully. Is this behavior expected since the image loads fine upon the second try?
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
Upon reaching this point, the process continues to the img.onload
and loads the image correctly thereafter.
What could be missing in this scenario? Should there be a delay introduced to wait for the image to load? Any suggestions on making it load later or any other potential solutions?