I am trying to convert an img URL to a var that I can use elsewhere in my code.
So far, I have the following approach:
function toDataUrl(src) {
// Create an Image object
var img = new Image();
// Add CORS approval to prevent a tainted canvas
img.crossOrigin = 'Anonymous';
// Load the image
img.src = src;
// make sure the load event fires for cached images too
if (img.complete || img.complete === undefined) {
// Flush cache
img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
// Try again
img.src = src;
}
img.onload = function() {
// Create an html canvas element
var canvas = document.createElement('CANVAS');
// Create a 2d context
var ctx = canvas.getContext('2d');
var dataURL;
// Resize the canavas to the original image dimensions
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
// Draw the image to a canvas
ctx.drawImage(this, 0, 0);
// Convert the canvas to a data url
dataURL = canvas.toDataURL(outputFormat);
// Mark the canvas to be ready for garbage
// collection
canvas = null;
// Return the data url via callback
// callback(dataURL);
return dataURL;
};
}
var myimg = toDataUrl('/media/signatures/signature.8.png');
However, myimg
returns undefined
. I think this is because it might be loading asynchronously. I have refered to this answer however it does not explain how to set the callback as a global variable.
How can I set myimg = dataURL
? Is there a way to do this without a callback?