doudao9896 2019-02-18 22:50
浏览 316

使用html2canvas将png保存到服务器

I am using a method from this tutorial to save a picture generated with html to a png or jpeg file in server.

I suspect there is an error in the original script but cannot find it

the picture should appear in the image_id div, but it does not.

here is my code:

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

the php file i use is the following:

<?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;
?>
  • 写回答

1条回答 默认 最新

  • duanben1324 2019-02-18 23:08
    关注

    It looks like the code is missing some end } and ) for ending of onrendered and 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>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!