I tried to convert the image to base64 string using javascript/angularjs following the code showed on this stacko page, you can also check the code in detail here.
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)
}
)
I call this function in the init inside the controller but when i load the page the image doesn't load the first time, but if i load the page again the image does load. I also made a button to call the function again, and as expected the image loads just fine after i load the page and press the button.
Debugging the code i found that the image only loads if it gets to the last if statement which, as by the detailed code, is flushing the cache. But since it's trying by the second time wouldn't this be the normal approach?
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
After getting here it goes on to img.onload
and loads the image again, this time the image loads just fine.
What am i missing? Do i need to do something to wait the image to load? Can i do something to make it load later? Or is it something else?