How to take screenshot of a div with JavaScript?

前端 未结 10 1501
误落风尘
误落风尘 2020-11-22 08:03

I am building something called the \"HTML Quiz\". It\'s completely ran on JavaScript and it\'s pretty cool.

At the end, a results box pops up that says \"Your Result

相关标签:
10条回答
  • 2020-11-22 08:21

    You can't take a screen-shot: it would be an irresponsible security risk to let you do so. However, you can:

    • Do things server-side and generate an image
    • Draw something similar to a Canvas and render that to an image (in a browser that supports it)
    • Use some other drawing library to draw directly to the image (slow, but would work on any browser)
    0 讨论(0)
  • 2020-11-22 08:24

    If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers

    Example "all-in-one" script script.php

    <?php if(isset($_GET['image'])):
        $image = $_GET['image'];
    
        if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
            $base64 = $match[2];
            $imageBody = base64_decode($base64);
            $imageFormat = $match[1];
    
            header('Content-type: application/octet-stream');
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private", false); // required for certain browsers
            header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".strlen($imageBody));
            echo $imageBody;
        }
        exit();
    endif;?>
    
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
    <canvas id="canvas" width="300" height="150"></canvas>
    <button id="btn">Save</button>
    <script>
        $(document).ready(function(){
            var canvas = document.getElementById('canvas');
            var oCtx = canvas.getContext("2d");
            oCtx.beginPath();
            oCtx.moveTo(0,0);
            oCtx.lineTo(300,150);
            oCtx.stroke();
    
            $('#btn').on('click', function(){
                // opens dialog but location doesnt change due to SaveAs Dialog
                document.location.href = '/script.php?image=' + canvas.toDataURL();
            });
        });
    </script>
    
    0 讨论(0)
  • 2020-11-22 08:28
    <script src="/assets/backend/js/html2canvas.min.js"></script>
    
    
    <script>
        $("#download").on('click', function(){
            html2canvas($("#printform"), {
                onrendered: function (canvas) {
                    var url = canvas.toDataURL();
    
                    var triggerDownload = $("<a>").attr("href", url).attr("download", getNowFormatDate()+"电子签名详细信息.jpeg").appendTo("body");
                    triggerDownload[0].click();
                    triggerDownload.remove();
                }
            });
        })
    </script>
    

    quotation

    0 讨论(0)
  • 2020-11-22 08:28

    As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are

    0 讨论(0)
  • 2020-11-22 08:28

    As far as I know its not possible with javascript.

    What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)

    0 讨论(0)
  • 2020-11-22 08:29

    After hours of research, I finally found a solution to take a screenshot of an element, even if the origin-clean FLAG is set (to prevent XSS), that´s why you can even capture for example Google Maps (in my case). I wrote a universal function to get a screenshot. The only thing you need in addition is the html2canvas library (https://html2canvas.hertzen.com/).

    Example:

    getScreenshotOfElement($("div#toBeCaptured").get(0), 0, 0, 100, 100, function(data) {
        // in the data variable there is the base64 image
        // exmaple for displaying the image in an <img>
        $("img#captured").attr("src", "data:image/png;base64,"+data);
    });
    

    Keep in mind console.log() and alert() won´t generate output if the size of the image is great.

    Function:

    function getScreenshotOfElement(element, posX, posY, width, height, callback) {
        html2canvas(element, {
            onrendered: function (canvas) {
                var context = canvas.getContext('2d');
                var imageData = context.getImageData(posX, posY, width, height).data;
                var outputCanvas = document.createElement('canvas');
                var outputContext = outputCanvas.getContext('2d');
                outputCanvas.width = width;
                outputCanvas.height = height;
    
                var idata = outputContext.createImageData(width, height);
                idata.data.set(imageData);
                outputContext.putImageData(idata, 0, 0);
                callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
            },
            width: width,
            height: height,
            useCORS: true,
            taintTest: false,
            allowTaint: false
        });
    }
    
    0 讨论(0)
提交回复
热议问题