Image to Base64
JavaScript
// This function does not return anything.
function convertImgToBase64(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback(dataURL);
canvas = null;
};
img.src = url;
}
var codedPic;
var purl = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
// convertImgToBase64 does not return anything, so codedPic will be assigned nothing and stay undefined.
var codedPic = convertImgToBase64(purl, function (base64Img) {
console.log('attempt 1: ' + base64Img);
// Now image is loaded, and you can assign the value into your global variable.
codedPic = base64Img;
// You just need to call the code that depends on codedPic from within the callback as a start point.
outputCodedPic();
});
var attemptNo = 2;
function outputCodedPic() {
console.log('attempt ' + attemptNo + ': ' + codedPic);
attemptNo += 1;
}
// If the code is called outside of the callback, codedPic may still have an undefined value.
outputCodedPic();