Search code examples
javascriptnode.jsgoogle-chrome-devtoolsscreenshotpuppeteer

Set Width and Height of Element Screenshot in Puppeteer


If I have this code:

const puppeteer = require('puppeteer');

var test = async () => {
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]});
  const page = await browser.newPage();
  await page.goto('https://community.wikia.com/wiki/Special:WikiActivity');
  let element =  await page.$('#WikiaMainContent');
  await page.setViewport({ width: 800, height: 1000}); // This is ignored
  await element.screenshot({path: "./wiki.png"});
  await browser.close(); 
}

test();

The screenshot is larger than the viewport.

How can I make it so that the screenshot has a width of 800px and height of 1000px?


Solution

  • You can use the clip option of elementHandle.screenshot() in conjunction with elementHandle.boundingBox() to set the width and height of an element screenshot.

    The example below will take a screenshot of an element, and clip the element if it exceeds the current viewport:

    await page.setViewport({
      width: 800,
      height: 1000,
    });
    
    const example = await page.$('#example');
    const bounding_box = await example.boundingBox();
    
    await example.screenshot({
      path: 'example.png',
      clip: {
        x: bounding_box.x,
        y: bounding_box.y,
        width: Math.min(bounding_box.width, page.viewport().width),
        height: Math.min(bounding_box.height, page.viewport().height),
      },
    });