Capture only current viewport not whole body as screenshot
Asked Answered
V

3

6

I'm using html2canvas to capture a screenshot of a site on different devices and send them to a storage via a XMLHTTPRequest.

Especially on sites with a lot of content the resulting screenshots tend to be very high and large, although most of the information in the screenshot is not relevant to what I need to caputure.

I've been trying to temper with the canvas element to have it only contain what I am currently seeing in the browser instead of capturing the whole body of the page, but without success.

Is it possible to tweak html2canvas in a way that allows to only capture the current window instead of the whole body?

Currently used code is:

html2canvas(document.body).then(function(canvas) {
        var img = canvas.toDataURL("image/png");
        ajax_post(img); 
    });
Voracity answered 21/5, 2015 at 13:54 Comment(0)
D
8

The existing answer isn't supported anymore, here is how I did it:

html2canvas(document.body, {
  x: window.scrollX,
  y: window.scrollY,
  width: window.innerWidth,
  height: window.innerHeight,
});
Diabolism answered 29/12, 2020 at 22:4 Comment(0)
M
3

The question is old but I had the same question, I looked at the code of html2canvas 5 and found how to do that.

Since other people could search for the same thing, here is the answer, just set the options.type to 'view':

html2canvas(document.body, { type: 'view' }).then(function(canvas) {
var img = canvas.toDataURL("image/png");
    ajax_post(img); 
});
Mousy answered 25/11, 2015 at 16:45 Comment(1)
This does not seem to be supported anymore. Any alternatives?Thermomotor
D
1

This code just works and is simple

html2canvas(document.body, { x: window.scrollX, y: window.scrollY, width: window.innerWidth, height: window.innerHeight, });

window.scrollX; Returns the number of pixels that the document has already been scrolled horizontally.

window.innerWidth and window.innerHeight; Returns the current frame's height and width:

Dove answered 29/3, 2021 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.