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?



No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the HTMLCanvasElement object's toDataURL function to get a data: URI with the image's contents.

When the quiz is finished, do this:

var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */

When the user clicks "Capture", do this:'', document.getElementById('the_canvas_element_id').toDataURL());

This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.


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.


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 an universal function to get a screenshot. The only thing you need in addition is the html2canvas library (


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 an output if the size of the image is great.


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);
            outputContext.putImageData(idata, 0, 0);
            callback(outputCanvas.toDataURL().replace("data:image/png;base64,", ""));
        width: width,
        height: height,
        useCORS: true,
        taintTest: false,
        allowTaint: false

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;

<script type='text/javascript' src=''></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
        var canvas = document.getElementById('canvas');
        var oCtx = canvas.getContext("2d");

        $('#btn').on('click', function(){
            // opens dialog but location doesnt change due to SaveAs Dialog
            document.location.href = '/script.php?image=' + canvas.toDataURL();

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

Another alternative is to use GrabzIt's JavaScript API all you need to do is pass the CSS selector of the div you want to capture. It will then create a screenshot of just that div.

<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
{"target": "#results", "bheight": -1, "height": -1, "width": -1}).Create();

There is more examples here solving how to capture HTML elements. For full disclosure I am the API creator.

<script src="/assets/backend/js/html2canvas.min.js"></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");



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


<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src="" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src=""></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<link rel="stylesheet" href="" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
    window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer", {
        animationEnabled: true,
        theme: "light2",
            text: "Simple Line Chart"
            includeZero: false
        data: [{        
            type: "line",       
            dataPoints: [
                { y: 450 },
                { y: 414},
                { y: 520, indexLabel: "highest",markerColor: "red", markerType: "triangle" },
                { y: 460 },
                { y: 450 },
                { y: 500 },
                { y: 480 },
                { y: 480 },
                { y: 410 , indexLabel: "lowest",markerColor: "DarkSlateGrey", markerType: "cross" },
                { y: 500 },
                { y: 480 },
                { y: 510 }


<body bgcolor="black">
<div id="wholebody">  
<a href="javascript:genScreenshotgraph()"><button style="background:aqua; cursor:pointer">Get Screenshot of Cars onl </button> </a>

<div id="car" align="center">
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>
    <i class="fa fa-car" style="font-size:20px;color:red;"></i>
    <i class="fa fa-car" style="font-size:50px;color:red;"></i>
    <i class="fa fa-car" style="font-size:60px;color:red;"></i>
    <i class="fa fa-car" style="font-size:70px;color:red;"></i>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src=""></script>

<div id="box1">


function genScreenshotgraph() 
    html2canvas($('#car'), {
      onrendered: function(canvas) {

        var imgData = canvas.toDataURL("image/jpeg");
        var pdf = new jsPDF();
        pdf.addImage(imgData, 'JPEG', 0, 0, -180, -180);"download.pdf");





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)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.