使用html2canvas将png保存到服务器

问题描述 投票:0回答:1

我正在使用this tutorial的方法将用html生成的图片保存到服务器中的png或jpeg文件中。

我怀疑原始脚本中有错误但找不到它

图片应该出现在image_id div中,但事实并非如此。

这是我的代码:

<body>
<div class='container' id="printableArea">
...here goes the div to output as png
</div>
<div id="image_id">
<img src="" alt="image" />
</div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>


     <script>
     html2canvas([document.getElementById('printableArea')], {

    onrendered: function (canvas) {
        var imagedata = canvas.toDataURL('image/png');
        var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
        //ajax call to save image inside folder}
        $.ajax({
            url: 'save_image.php',
            data: {
                   imgdata:imgdata
                   },
            type: 'post',
            success: function (response) {   
               console.log(response);
               $('#image_id img').attr('src', response)

        }
    });
    }
    </script>        

我使用的php文件如下:

<?php 
$imagedata = base64_decode($_POST['imgdata']);
$filename = md5(uniqid(rand(), true));
//path where you want to upload image
$file = $_SERVER['DOCUMENT_ROOT'] . '/images/'.$filename.'.png';
$imageurl  = 'http://***.com/images/'.$filename.'.png';
file_put_contents($file,$imagedata);
echo $imageurl;
?>
javascript php ajax html2canvas
1个回答
0
投票

看起来代码缺少某些结尾}和)结束onrendered和html2canvas:

    <script>
 html2canvas([document.getElementById('printableArea')], {

onrendered: function (canvas) {
    var imagedata = canvas.toDataURL('image/png');
    var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
        $.ajax({
            url: 'save_image.php',
            data: {
                   imgdata:imgdata
                   },
            type: 'post',
            success: function (response) {   
               console.log(response);
               $('#image_id img').attr('src', response);

        }
    });
}});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.