Skip to content

Instantly share code, notes, and snippets.

@mhsattarian
Last active July 9, 2020 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhsattarian/8f380c851b2eaaae11b299f330f66670 to your computer and use it in GitHub Desktop.
Save mhsattarian/8f380c851b2eaaae11b299f330f66670 to your computer and use it in GitHub Desktop.
// Code from https://github.com/leighhalliday/generate-og-image/blob/master/src/chromium.ts
// and https://github.com/wesbos/wesbos/blob/master/functions/ogimage/ogimage.js
// and thanks wes.bos for the video on this at https://youtu.be/A0Ww-SU7K5E
async function getScreenshot(html, isDev) {
const options = await getOptions(isDev);
console.log("📸");
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
await page.setViewport({ width: 720, height: 1920, deviceScaleFactor: 1.5 });
await page.setContent(html, {
waitUntil: ["networkidle0", "domcontentloaded"],
});
// calculate the content bbox
const rect = await page.evaluate((selector) => {
const element = document.querySelector(selector);
const { x, y, width, height } = element.getBoundingClientRect();
return { left: x, top: y, width, height, id: element.id };
}, ".twitter-tweet");
// screen shot only the rect
let padding = 0;
return page.screenshot({
type: "jpeg",
quality: 100,
clip: {
x: rect.left - padding,
y: rect.top - padding,
width: rect.width + padding * 2,
height: rect.height + padding * 2,
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment