[javascript] How to take screenshot of a div with JavaScript?

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 Results:" and it shows how much time they took, what percentage they got, and how many questions they got right out of 10. I would like to have a button that says "Capture results" and have it somehow take a screenshot or something of the div, and then just show the image captured on the page where they can right click and "Save image as."

I really would love to do this so they can share their results with others. I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.

Does anyone know a way to do this or something similar?

This question is related to javascript jquery html

The answer is


It's to simple you can use this code for capture the screenshot of particular area you have to define the div id in html2canvas. I'm using here 2 div-:

div id="car"
div id ="chartContainer"
if you want to capture only cars then use car i'm capture here car only you can change chartContainer for capture the graph html2canvas($('#car') copy and paste this code

_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
<script>_x000D_
    window.onload = function () {_x000D_
    _x000D_
    var chart = new CanvasJS.Chart("chartContainer", {_x000D_
        animationEnabled: true,_x000D_
        theme: "light2",_x000D_
        title:{_x000D_
            text: "Simple Line Chart"_x000D_
        },_x000D_
        axisY:{_x000D_
            includeZero: false_x000D_
        },_x000D_
        data: [{        _x000D_
            type: "line",       _x000D_
            dataPoints: [_x000D_
                { y: 450 },_x000D_
                { y: 414},_x000D_
                { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },_x000D_
                { y: 460 },_x000D_
                { y: 450 },_x000D_
                { y: 500 },_x000D_
                { y: 480 },_x000D_
                { y: 480 },_x000D_
                { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },_x000D_
                { y: 500 },_x000D_
                { y: 480 },_x000D_
                { y: 510 }_x000D_
_x000D_
            ]_x000D_
        }]_x000D_
    });_x000D_
    chart.render();_x000D_
    _x000D_
    }_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body bgcolor="black">_x000D_
<div id="wholebody">  _x000D_
<a href="javascript:genScreenshotgraph()"><button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button> </a>_x000D_
_x000D_
<div id="car" align="center">_x000D_
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:20px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>_x000D_
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>_x000D_
</div>_x000D_
<br>_x000D_
<div id="chartContainer" style="height: 370px; width: 100%;"></div>_x000D_
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>_x000D_
_x000D_
<div id="box1">_x000D_
</div>_x000D_
</div>>_x000D_
</body>_x000D_
_x000D_
<script>_x000D_
_x000D_
function genScreenshotgraph() _x000D_
{_x000D_
    html2canvas($('#car'), {_x000D_
        _x000D_
      onrendered: function(canvas) {_x000D_
_x000D_
        var imgData = canvas.toDataURL("image/jpeg");_x000D_
        var pdf = new jsPDF();_x000D_
        pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);_x000D_
        pdf.save("download.pdf");_x000D_
        _x000D_
      _x000D_
      _x000D_
      }_x000D_
     });_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


var shot1=imagify($('#widget')[0], (base64) => {
  $('img.screenshot').attr('src', base64);
});

Take a look at htmlshot package , then, check deeply the client side section:

npm install htmlshot

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
    });
}

<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


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


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)


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)

This is an expansion of @Dathan's answer, using html2canvas and FileSaver.js.

$(function() { 
    $("#btnSave").click(function() { 
        html2canvas($("#widget"), {
            onrendered: function(canvas) {
                theCanvas = canvas;


                canvas.toBlob(function(blob) {
                    saveAs(blob, "Dashboard.png"); 
                });
            }
        });
    });
});

This code block waits for the button with the id btnSave to be clicked. When it is, it converts the widget div to a canvas element and then uses the saveAs() FileSaver interface (via FileSaver.js in browsers that don't support it natively) to save the div as an image named "Dashboard.png".

An example of this working is available at this fiddle.


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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment