如何使用 puppeteer 将 canvas 保存为图像?

How to save a canvas as an image using puppeteer?

我正在尝试加载带有 canvas 的页面,然后将其另存为图像。

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

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

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

但是 canvas 返回 null。

在您的示例中,canvas 在 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(); }