在Puppeteer中设置元素截图的宽度和高度

问题描述 投票:2回答:2

如果我有这个代码:

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();

屏幕截图大于视口。

我怎样才能使截图有width800pxheight1000px

javascript node.js google-chrome-devtools screenshot puppeteer
2个回答
9
投票

您可以使用clipelementHandle.screenshot()选项与elementHandle.boundingBox()一起设置元素截图的widthheight

下面的示例将截取元素的屏幕截图,如果元素超出当前视口,则剪切该元素:

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),
  },
});

1
投票

我在前面使用html2canvas有一个更好的解决方案:

https://gist.github.com/homam/3162383c8b22e7af691085e77cdbb414

或者在后端使用puppeteer和html2canvas:

const screenshot = await page.evaluate(async () => {
   const canvasElement = await html2canvas($("div")[0], {
        // useCORS: true,
   });

   let image = Canvas2Image.convertToImage(
        canvasElement,
        $(canvasElement).width(),
        $(canvasElement).height(),
        "png"
    );
    console.log(image.src)
    return image.src;
})
var fs = require('fs');
// strip off the data: url prefix to get just the base64-encoded bytes
var data = screenshot.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(`./screenshots/div-${Date.now()}-.png`, buf);

完整代码:https://github.com/davidtorroija/screenshot-of-div-e2e/blob/master/README.md

这是更好的,因为很容易截取一个巨大的div的截图,而不需要滚动,你不会失去div的任何部分

© www.soinside.com 2019 - 2024. All rights reserved.