使用html2canvas在文件夹中生成图像的阵列图像

时间:2014-01-15 17:42:01

标签: javascript php jquery arrays html2canvas

我将所有子图像src存储在Array中,我创建了示例模板,并且在数组循环中我正在更改src并且他们想要在图像中转换它们。但只有最后4个数组值保存为图像。这是ajax问题还是什么?

HTML code:

<div id="present_sample" style="display:">
<img id="one" src="img/Tulips.jpg" /> 
<img id="two" class="alignright" src="img/Tulips.jpg" /> 
<br/>
<img id="three" src="img/Tulips.jpg" /> 
<img id="four" class="alignright" src="img/Tulips.jpg" /> 

JQuery代码:

 $('#convert').click(function()
 {
 var images = $('#links a').children('img').map(function(){
 return $(this).attr('src') }).get();
    console.log(images);

    //$('#gallery_pic').append(images);
     var side=1;
      var data;
     for (i = 0; i < images.length; i++) {


        console.log('Top i is '+i);
        console.log('Group*******');
        console.log(i+','+images[i]);
        $('#one').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#two').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#three').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#four').attr("src", images[i]);
        console.log('Group Ends');
        html2canvas([document.getElementById('present_sample')], {
    onrendered: function (canvas) {
        $('canvas').html(canvas);
        var data = canvas.toDataURL('image/png');
        // AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server

        $.ajax({
          type: "POST",
          url: 'download.php',
          data: {
          image: data},
           success:function(data)   { 
          alert('Ajax return is'+data); 

            }
            });

        }

       });

});

PHP代码:

<?php 
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) { 

    // get the image data
    $data = $_POST['image'];

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    //Image name
    //$filename ="image". md5(uniqid()) . '.png';
    $filename ="image". md5(uniqid()) . '.jpg';

    $file = "download/".$filename;

  // decode the image data and save it to file
    file_put_contents($file,$data);

    echo "successfully downloaded in folder";


}
?>  

1 个答案:

答案 0 :(得分:0)

您只需使用one ajax request即可避免此问题,即在for循环结束后进行ajax调用,然后将所有数据附加到data变量,并且在循环结束时,只进行一次ajax调用。

注意:在ajax循环中for调用的这个问题已经在很多线程中讨论过了,看看是否有帮助:

http://www.ravenglass.com/blog/index.cfm/2013/3/5/FOR-Loops-Overwriting-Ajax-Responses-and-how-to-fix

Ajax call within jquery each loop

jQuery AJAX solution inside each() loop