是否有一种方法将html渲染成PNG那样的图像?我知道这是可能的与画布,但我想渲染标准的html元素,如div为例。


当前回答

我在Chrome、Firefox和MS Edge上使用的唯一一个库是rasterizeHTML。它输出比HTML2Canvas更好的质量,并且仍然受支持,不像HTML2Canvas。

获取元素和下载为PNG

var node= document.getElementById("elementId");
var canvas = document.createElement("canvas");
canvas.height = node.offsetHeight;
canvas.width = node.offsetWidth;
var name = "test.png"

rasterizeHTML.drawHTML(node.outerHTML, canvas)
     .then(function (renderResult) {
            if (navigator.msSaveBlob) {
                window.navigator.msSaveBlob(canvas.msToBlob(), name);
            } else {
                const a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                a.href = canvas.toDataURL();
                a.download = name;
                a.click();
                document.body.removeChild(a);
            }
     });

其他回答

你可以添加引用HtmlRenderer到你的项目,并执行以下操作:

string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));

使用剧作家的page.screen()可以非常容易地截取屏幕截图。例如使用Python(但它也适用于Node.js, Java和.NET):

from playwright.async_api import async_playwright

async with async_playwright() as p:
     browser = await p.chromium.launch()
     page = await browser.new_page()
     await page.goto('https://google.com')
     await page.screenshot(path=f'screenshot.png')
     await browser.close()

我知道这是一个已经有很多答案的老问题,但我仍然花了很多时间去做我想做的事情:

给定一个HTML文件,从命令行生成一个带有透明背景的(png)图像

使用Chrome headless (version 74.0.3729.157),实际上很容易:

"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless --screenshot --window-size=256,256 --default-background-color=0 button.html

命令使用说明:

you run Chrome from the command line (here shown for the Mac, but assuming similar on Windows or Linux) --headless runs Chrome without opening it and exits after the command completes --screenshot will capture a screenshot (note that it generates a file called screenshot.png in the folder where the command is run) --window-size allow to only capture a portion of the screen (format is --window-size=width,height) --default-background-color=0 is the magic trick that tells Chrome to use a transparent background, not the default white color finally you provide the html file (as a url either local or remote...)

这就是我所做的。

注意:请检查App.js的代码。

链接到源代码

如果你喜欢它,你可以掉一颗星。✌️

更新:

import * as htmlToImage from 'html-to-image';
import download from 'downloadjs';

import logo from './logo.svg';
import './App.css';

const App = () => {
  const onButtonClick = () => {
    var domElement = document.getElementById('my-node');
    htmlToImage.toJpeg(domElement)
      .then(function (dataUrl) {
        console.log(dataUrl);
        download(dataUrl, 'image.jpeg');
      })
      .catch(function (error) {
        console.error('oops, something went wrong!', error);
      });
  };
  return (
    <div className="App" id="my-node">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a><br></br>
        <button onClick={onButtonClick}>Download as JPEG</button>
      </header>
    </div>
  );
}

export default App;

你可以使用PhantomJS,这是一个无头webkit (safari和chrome(直到最近)的渲染引擎)驱动程序。您可以在这里学习如何对页面进行屏幕捕获。希望有帮助!