In your function get_front_image
you assign an empty string to the variable front_image
, then you call the html2canvas
function, which has an onrendered
function. This function is called asynchronous, so by the time you're returning the front_image
variable, the onrendered
function is not called yet, which means front_image
is still an empty string.
Mostly when doing asynchronous stuff, you'll work with callback functions. Here that could look something like this:
function get_front_image(callbackFunction){
var front_image="";
html2canvas($('#selector'), {
onrendered: function(canvas) {
front_image=canvas.toDataURL();
callbackFunction(front_image);
}
});
}
var f;
get_front_image(function(value){
f = value;
alert(f); //will return your value
});
alert(f); //Wont alert your value
To make it clear in which order what's executed:
- Var f is declared
var f;
get_fron_image
is called, and the html2canvas function is called. This is asynchronous, so the onrendered
function will be called just when it's finished, and we can't know when this will happen.
- The
alert(f); //wont alert your value
line is executed. As the onrendered
function hasn't been called yet, f
does not have a value yet.
- Eventually, the
onrendered
function is executed, and the callbackFunction
is called, where alert(f);
shows your value as expected. Whatever you want to do with your variable f
must happen in the callbackFunction in order to work.