如何获取puppeteer渲染后的图片

imagify插件可以用HTML将文本渲染成带背景的图片,直接用ctx.puppeteer.render(html文本)得到的是空白背景的图,怎样能得到imagify那样带背景的呢

2 个赞

ctx.puppeteer.render 这个方法是没错的,可能你的这个 html文本 渲染出来就是空白的,你可以试着保存 html 文本为一个 .html 文件,然后用浏览器打开这个 .html 文件

2 个赞

可能需要更多信息,例如代码才能知道具体情况。

imagify 使用了由 pptr 插件扩展的 <html> 元素来渲染,部分代码:

// css via js
const htmlStyle = {
    'font-size': '1.3rem',
    padding: '2rem',
    'background': `${config.background ? `url(${config.background})` : '#fff'}`,
    'background-size': 'contain',
    'background-repeat': 'no-repeat',
}
const pStyle = {
    'margin': '12px 22px 12px 22px',
}
const cardStyle = {
    padding: '24px 12px',
    background: 'rgba(255, 255, 255, 0.6)',
    'border-radius': '15px',
    'backdrop-filter': `blur(${config.blur}px)`,
    'box-shadow': '0px 0px 15px rgba(0, 0, 0, 0.3)',
}
const footerStyle = {
    'font-size': '0.85rem',
    background: '#333333',
    color: '#ffffff',
    padding: '18px',
    margin: '1rem -2rem -2rem -2rem'
}
//render by <html> element: 
<html style={htmlStyle}>
  <div style={cardStyle}>
    {contentMapper.map(ele => <p style={pStyle}>{ele}</p>)}
  </div>
  <footer style={footerStyle}>Generated by Koishi {version} / koishi-plugin-imagify v{pv}</footer>
</html>
2 个赞

我直接把这段代码放进ctx.puppeteer.render的参数里了,但这个参数应该传string而不是Element,导致出错。Element能转为string吗?如果直接用toString()会出现[object Object]这样的缩写,导致渲染不出背景

1 个赞

你需要将你的文件重新命名为例如 index.tsx,并直接返回这一段。

2 个赞

imagify 重构了,并使用了 ctx.puppeteer.render 渲染图片,可以看一看:

1 个赞


最新版效果是这样的,很宽字很小下面一大片空白不能加载背景图,这是预期现象吗

2 个赞

背景图没法加载吗?这里测试是没问题的,看看你是如何配置的

很宽字很小这个不是预期的,似乎是 ctx.pptr.render 造成的,具体原因还没有找到。

3 个赞