通过使用html2canvas循环生成图像

时间:2018-11-20 18:39:17

标签: canvas html2canvas

在我的页面中,我有多个div块。 当我用html2canvas生成图像时,我需要知道每个元素ID,但是控制台每次返回最后一个块ID时都需要知道。 我可以获取正确的ID吗?

例如

   <div class='myBlock' id= 'image24' data-id='24'> .....  </div>
   <div class='myBlock' id= 'image30' data-id='30'> .....  </div>
   <div class='myBlock' id= 'image32' data-id='32'> .....  </div>
   <div class='myBlock' id= 'image45' data-id='45'> .....  </div>
   <div class='myBlock' id= 'image58' data-id='58'> .....  </div>
   <div class='myBlock' id= 'image62' data-id='62'> .....  </div>

通过HTML2Canvas生成图像

      $.each($(".thumbnailDetails"), function(){

        elId = $(this).attr('id');

        html2canvas($("#target"+elId), {
             onrendered: function(canvas) {
                .....generate Image ....
                console.log(elId); // always return last id
             }
        });


 I need to get for each image his own id, but i always get the last one.

1 个答案:

答案 0 :(得分:0)

解决方案

  i      = 0;
  ids    = [];
  images = {};

  $("...").each(function() {
       ids = $(this).attr('data-id'); //returns each image id            
  });

  someFunction() {
       html2canvas($("#image"+ids[i]), {
          onrendered: function(canvas) {
              //generate canvas
              i++;

              if(i == ids.legth) {
                 //my ajax

              } else {
                 someFunction();

              }
          }
       });

  }

  someFunction();