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.
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.
来源:https://stackoverflow.com/questions/16275799/looping-html2canvas