Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

In short, try this:

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

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

Solution 2:

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.

Solution 3:

if you are using react, try async/await.

mark your javascript function as async. Example,

asyncprintDocument(){
  let canvas = await html2canvas(printDiv)
  // canvas to image stuff
}

visit https://medium.com/@patarkf/synchronize-your-asynchronous-code-using-javascripts-async-await-5f3fa5b1366d for more information.

Post a Comment for "Looping Html2canvas"