循环html2canvas [英] Looping html2canvas

查看:621
本文介绍了循环html2canvas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试在for循环中实现html2canvas脚本时遇到了一些麻烦。

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

我正在编写一个使用数据数组的Javascript函数修改一组元素的样式,将容器div捕获为画布,将其转换为图像,将其附加到文档正文,然后移动到数组的下一个索引。

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);
    }
});

通过逐步完成脚本,我发现它不是在等待画布要在进入for循环的下一次迭代之前进行渲染,这会导致我尝试捕获的元素发生变化但渲染的每个图像看起来完全相同(作为数组中的最终索引)。

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).

在画布渲染时,有没有办法延迟脚本一秒钟?我已经尝试过使用 setTimeout()而且似乎无法找到任何其他延迟脚本的方法,我不熟悉 onrendered 部分代码有效。

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.

推荐答案

您可能想要了解异步工作流程(例如 https: //github.com/caolan/async

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

简而言之,试试这个:

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

这就是我们想要仅在onrendered完成时调用 nextStep

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

这篇关于循环html2canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆