Search code examples
javascriptcanvashtml2canvas

html2canvas while updating canvas data


plot array is a global variable., while console.log the canvas parameter inside the onrendered function .., data exists. but.. when logged outside the function.., gives empty array

html2canvas(document.querySelector(".classone"),{
  onrendered:function(canvas){
      plot_array.push({canvasdata:canvas.toDataURL('image/png')});
  }
});

console.log(plot_array);

the plot array logged as empty... ??


Solution

  • Welcome to js. html2canvas is an asynchronous function. In earlier versions, you had to provide a callback function as a parameter, nowadays, it does use Promises. In any case, you just have to set a counter variable before your calls, and increment it in the callbacks. Once the counter reaches the numbers of calls to be made, all asynchronous functions are done, you can continue to your ajax call. So with your actual code (which uses an old version of h2c) Before the loop :var rendered = 0; and then in the loop h2c(... onrendered: function(){...if(++rendered===calls.length){ajax()})})

    as answered by Kaiido