Looping html2canvas

若如初见. 提交于 2019-12-03 17:01:43

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.

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.

if you are using react, try async/await.

mark your javascript function as async. Example,

async printDocument(){
  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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!