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;
console.log('attempt 2 in callback: ' + codedPic);
});
// Image is not loaded yet,
console.log('attempt 2: ' + codedPic);