0

我正在尝试使用画布加载页面,然后将其另存为图像。

例如,这个页面。在 Chrome 上,我可以右键单击页面右上角带有圆圈的画布,然后单击保存图像。我想做同样的事情,但通过 NodeJS 和 Puppeteer。这可能吗?

到目前为止,我正在尝试通过

const express = require('express')
const router = express.Router()
const puppeteer = require('puppeteer')
const { Cluster } = require('puppeteer-cluster')

(async () => {
    
    const cluster = await Cluster.launch({
        concurrency: Cluster.CONCURRENCY_PAGE,
        maxConcurrency: 2,
    })
    
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    await cluster.task(async({ page, data: url }) => {
        // let starmapId = 'celestial-canvas'

        await page.goto(url)
        const canvas = await page.evaluate(() => document.querySelector('#myCanvas'))
        return canvas  // .toDataURL()
    })
    
    router.get('/export/canvas', function(req, res) {
        
        // Get URL
        var url = 'https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_tut_path2'
        
        cluster.execute(url).then( canvas => {
            console.log(canvas)
            res.send(canvas)
        })
    })
    
})();

module.exports = router

但是画布返回空值。

4

1 回答 1

0

在您的示例中,画布位于 iframe 内。因此,您需要先获取帧,然后才能使用数据 URL 传输字符串:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch(/* { headless: false, defaultViewport: null } */);

try {
  const [page] = await browser.pages();

  await page.goto('https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_canvas_tut_path2');

  const frame = await (await page.$('#iframeResult')).contentFrame();

  const data = await frame.evaluate(() => {
    return document.querySelector('#myCanvas').toDataURL();
  });
  console.log(data); // data:image/png;base64,iVBORw0K...
} catch(err) { console.error(err); } finally { await browser.close(); }
于 2021-01-27T22:48:56.847 回答