How to take screenshot of a div with JavaScript?

前端 未结 10 1696
误落风尘
误落风尘 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: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#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
        });
    }
    

提交回复
热议问题