最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Canvas drawing not loading in puppeteer - Stack Overflow

programmeradmin1浏览0评论

I need to generate snapshots for seo. I am using puppeteer(headless chrome) for this purpose. On main page i have a canvas, on which i start to draw once the ponent has mounted (my main site is in react).

Issue is that when i get the html from puppeteer, the drawing on the canvas is not there.

In puppeteer code i wait till the content is not loaded.

html = await page.content()

How can i make puppeteer wait till the point canvas is not painted.

I need to generate snapshots for seo. I am using puppeteer(headless chrome) for this purpose. On main page i have a canvas, on which i start to draw once the ponent has mounted (my main site is in react).

Issue is that when i get the html from puppeteer, the drawing on the canvas is not there.

In puppeteer code i wait till the content is not loaded.

html = await page.content()

How can i make puppeteer wait till the point canvas is not painted.

Share Improve this question asked May 16, 2019 at 9:25 Anurag92Anurag92 1242 silver badges9 bronze badges 4
  • Do you want to wait until something happens or do you want to get the image from the Canvas? Because you cannot read the image from the canvas via page.content. This will only return HTML code. – Thomas Dondorf Commented May 16, 2019 at 15:01
  • Something is drawn on the canvas, i tried waiting for some 20 seconds, but still i am not able to get what is drawn on the canvas, Though in headless chrome I am able to see the drawing on the canvas. Seems like puppeteer simply replicates the html. – Anurag92 Commented May 17, 2019 at 3:44
  • Added an answer that shows you how to get the image shown in the canvas :) – Thomas Dondorf Commented May 17, 2019 at 5:34
  • Show us how you do get your snapshot. – Kaiido Commented May 17, 2019 at 5:45
Add a ment  | 

1 Answer 1

Reset to default 6

page.content will only return the HTML representation of the DOM. To get the actual image of a canvas inside the DOM, you can use the function toDataURL. This will return the image that is shown in a base64-encoded string.

Code sample

const dataUrl = await page.evaluate(() => {
    const canvas = document.querySelector("#canvas-selector");
    return canvas.toDataURL();
});

// dataUrl looks like this: "data:image/png;base64,iVBORw..."
const base64String = dataUrl.substr(dataUrl.indexOf(',') + 1); // get everything after the ma
const imgBuffer = Buffer.from(base64String, 'base64'); // 
fs.writeFileSync('image.png', imgBuffer);

The evaluate call will return the base64 encoded buffer of the image. You need to first remove the "data:...," from that and then you can put that into a buffer. The buffer can then be saved (or handled in any other way).

发布评论

评论列表(0)

  1. 暂无评论