2014-01-15 57 views
0

我存储所有的孩子图像src数组中,我已经创建了示例模板和数组循环我正在更改src,他们想要在图像中转换它们。但只有最后4个数组值被保存为图像。这是阿贾克斯问题还是什么?阵列图像使用html2canvas生成文件夹中的图像

HTML代码:

<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"; 


} 
?> 
+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

+0

如果我只是通过在图像src中设置来删除ajax并检查数据,则会创建2个图像,但两者都是相同的。我不明白为什么前4个图像重叠最后 – anam

+0

你的意思是2套4图像创建,但两套都是一样的? – gaurav5430

+0

yup ...你明白我的观点 – anam