Search code examples
javascriptphphtml2canvas

DOM created screenshots as PNG files


I am using html2canvas.js to create a screenshot of a webpage. The only thing is that I don't know how to transfer this data to an image file format so that I can save it and link it in the database.

This is my current code:

<script language="Javascript">
    setInterval(function() {
        html2canvas(document.body, {
            onrendered: function(canvas2) {
                context.drawImage(video, 0, 0, 240, 180);
                $.post(
                    "' . self::get_link('save_screenshots') . '",
                    "user_id=' . module_security::get_loggedin_id() .
                    '&screenshot=" + encodeURI(canvas2.toDataURL())
                );
                document.body.appendChild(canvas2)
            }
        })
    }, 1*60*1000);
</script>

Solution

  • This may help you:

    <?php
        // requires php5
        define('UPLOAD_DIR', 'your/images/directory/');
        $img = $_POST['img'];
        $img = str_replace('data:image/png;base64,', '', $img);
        $img = str_replace(' ', '+', $img);
        $data = base64_decode($img);
        $img_file = UPLOAD_DIR . uniqid() . '.png';
        $success = file_put_contents($img_file, $data);
        if($img_file){
            // store the link to database
        } else{
           //return error msg
        }
    
    ?>