Search code examples
javascripthtml2canvas

html2canvas option type: 'view' still render full body


I would like to get only viewport screenshot from the library html2canvas.js, set option type to 'view' should do the trick but i'm still getting the entire body.

Don't really get why this is not working actually.

Here is the code i'm currently running:

html2canvas(document.body, { type: 'view' }).then(function(canvas) {
    var img = canvas.toDataURL("image/png");
    $('.ticket-img').attr('src', img);
});

Solution

  • There is no such option as { type: 'view' }. If you are trying to capture just what is visible to the user there isn't an exact settings for that.

    I'd probably say you'd need to process the output after the screenshot was taken. So take the screenshot then use the window scrollX/scrollY and window width/height to crop the resulting canvas.

    Something like

    function clip( srcCanvas, x, y, width, height ) {
        var destCanvas = document.createElement("canvas");
        var destCtx = destCanvas.getContext("2d");
    
        destCanvas.width = width;
        destCanvas.height = height;
    
        destCtx.drawImage( srcCanvas.getImageData(x,y,width,height), 0, 0 );
        return destCanvas;
    }