How to take screenshot of a div with JavaScript?

前端 未结 10 1749
误落风尘
误落风尘 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:39

    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.

提交回复
热议问题