Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture only current viewport not whole body as screenshot

Tags:

html2canvas

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); 
    });
like image 475
user4924966 Avatar asked May 21 '15 13:05

user4924966


2 Answers

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,
});
like image 175
Collierre Avatar answered Sep 28 '22 08:09

Collierre


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); 
});
like image 20
acemtp Avatar answered Sep 28 '22 07:09

acemtp