Looping html2canvas

GeneralBison picture GeneralBison · Apr 29, 2013 · Viewed 7.4k times · Source

I'm having a bit of trouble trying to implement the html2canvas script in a for loop.

I'm writing a Javascript function that uses an array of data to modify the style of a group of elements, captures the container div as a canvas, converts it into an image, appends it to the document body and then moves on to the next index of the array.

The part where I'm having trouble is at the very end of my loop:

html2canvas(document.getElementById("background"), {
    onrendered: function(canvas) {
        var imgdata = canvas.toDataURL("image/png");
        var obj = document.createElement("img");
        obj.src=imgdata;
        document.body.appendChild(obj);
    }
});

By going through the script step by step I've found that it isn't waiting for the canvas to be rendered before moving on to the next iteration of the for loop, this results in the element I'm trying to capture changing but every image being rendered looking exactly the same (as the final index in the array).

Is there a way to delay the script for a second while the canvas renders? I've tried using setTimeout() and can't seem to find any other ways of delaying the script, I am unfamiliar with how the onrendered part of the code works.

If my explanation is unclear I will prepare some suitable examples soon.

Answer

neo picture neo · Apr 29, 2013

You may want to read about asynchronous workflow (like https://github.com/caolan/async)

In short, try this:

var i = 0;
function nextStep(){
  i++;
  if(i >= 30) return;
  // some body
  html2canvas(...
    onrendered: function(canvas){
      // that img stuff
      nextStep();
    }
  }
}
nextStep();

That is we want to call nextStep only when onrendered has finished.