0

I'm working with html2canvas and I have the next function

hml2canvas($('body'), {
   onrendered: function(canvas) {           
         data = canvas.toDataURL('image/jpeg');
    }
});

Now, I want to return the data value, so I tried this

html2canvas($('body'), {
    onrendered: (this, imgBase64)         
});

var data;
function imgBase64(canvas) {
     data = canvas.toDataURL('image/jpeg');
}
console.log(data);

but when I see the console I get "undefined". If I put console.log(data); inside the imgBase64 function I get the base64 of the image, but I need the data out of that function to make another work with it. Any ideas? Thanks.

Jefferson
  • 794
  • 10
  • 24
  • 1
    You're logging `data` before the `imgBase64` is ever called. – Jack Feb 05 '13 at 20:50
  • See if this helps: http://stackoverflow.com/search?q=asynchronous+variable+javascript – elclanrs Feb 05 '13 at 20:51
  • 1
    what are you trying to accomplish with `onrendered: (this, imgBase64)`? I'm not even sure that's valid syntax. – jbabey Feb 05 '13 at 20:52
  • Asynchronous code explained through Ajax: http://stackoverflow.com/q/14220321/1331430 the same principle applies. – Fabrício Matté Feb 05 '13 at 20:54
  • @jbabey: Technically it is valid syntax, two expressions separated by a comma operator but probably not what OP intended to do. Check this jsbin, it throws all sorts of warnings but the code works http://jsbin.com/ucomir/1/edit – elclanrs Feb 05 '13 at 20:56
  • The comma operator will return the last expression's return value after evaluating the expressions. – Fabrício Matté Feb 05 '13 at 20:58
  • Minifiers use the comma operator everywhere, it's quite useful in one liner return statements, ie `return this.foo = 'foo', this;` – elclanrs Feb 05 '13 at 21:04
  • @elclanrs thanks but the link didn't work for me. About this [comment](http://stackoverflow.com/questions/14716630/how-to-return-value-from-this-javascript-function#comment20586257_14716630) what should be the proper way? – Jefferson Feb 05 '13 at 21:32

1 Answers1

0

I found this answer so I modified to adapt to my needs.

var html2obj = html2canvas($('body'));
var queue  = html2obj.parse();
var canvas = html2obj.render(queue);
var data = canvas.toDataURL('image/jpeg');

this way I have the data to use later.

Community
  • 1
  • 1
Jefferson
  • 794
  • 10
  • 24