Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping html2canvas

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.

like image 427
GeneralBison Avatar asked Apr 29 '13 09:04

GeneralBison


2 Answers

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.

like image 178
neo Avatar answered Sep 26 '22 10:09

neo


Synchronous code mean that each statement in your code is executed one after the other.

Asynchronous code is the opposite, it takes statements outside of the main program flow.

html2canvas works asynchronously so your loop may finish, and i become 20 before executing html2canvas code..

One solution is like this:

for (let i = 0; i < array.length; i++) {
  generateCanvas(i);
}

function generateCanvas(i){
  html2canvas(..
    // you can use i here
  )
}

by wrapping the html2canvas code in a function, you ensure that the value of "i" remains as you intended.

like image 42
Basel Issmail Avatar answered Sep 26 '22 10:09

Basel Issmail