是否有一种方法将html渲染成PNG那样的图像?我知道这是可能的与画布,但我想渲染标准的html元素,如div为例。
当前回答
你可以使用像wkhtmltopdf这样的HTML转PDF工具。然后你可以使用像imagemagick这样的PDF图像工具。不可否认,这是服务器端,一个非常复杂的过程…
其他回答
你可以使用PhantomJS,这是一个无头webkit (safari和chrome(直到最近)的渲染引擎)驱动程序。您可以在这里学习如何对页面进行屏幕捕获。希望有帮助!
是的,你可以用HTML2Canvas库它渲染你的HTML代码到画布。 它提供了将html从特定div转换为图像的选项,然后使用canvas2image将图像本地下载到您的文件系统中。
链接源代码
html2canvas(document.querySelector('#screenscoot'), {
onrendered: function(canvas) {
// document.body.appendChild(canvas);
return Canvas2Image.saveAsPNG(canvas);
}
});
我知道这是一个已经有很多答案的老问题,但我仍然花了很多时间去做我想做的事情:
给定一个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...)
我不认为这是最好的答案,但它似乎很有趣,可以发布。
编写一个应用程序,打开您最喜欢的浏览器到所需的HTML文档,适当大小的窗口,并采取屏幕截图。然后,删除图像的边界。
安装幻影
$ npm install phantomjs
用以下代码创建一个文件github.js
var page = require('webpage').create();
//viewportSize being the actual size of the headless browser
page.viewportSize = { width: 1024, height: 768 };
page.open('http://github.com/', function() {
page.render('github.png');
phantom.exit();
});
将文件作为参数传递给phantomjs
$ phantomjs github.js
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 我如何在网站上使用谷歌的Roboto字体?
- 父ng-repeat从子ng-repeat的访问索引
- 如何禁用文本区域大小调整?
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何在HTML5中改变视频的播放速度?
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 如何把滚动条只为情态体?
- 与push()相反;