NodeJS

使用PhantomJS实现网页快照

2017-3-30 1886字 8,205

前言

公司要搞画谱的步骤截图,无奈ios截图太消耗手机内存了,影响用户体验,只好生成好图片交给IOS了。

简介

PhantomJS 是一个无界面的 Webkit 内核浏览器,对 DOM 操作、CSS 选择器、JSON、 Canvas 和 SVG 等 WEB 标准有非常快的、原生的支持。总之 PhantomJS 就是一个有 API 的浏览器,可以用来进行网页截图、自动化测试等。
官网:http://phantomjs.org/build.html

npm安装PhantomJS

PHANTOMJS_CDNURL=https://npm.taobao.org/dist/phantomjs npm install -g phantomjs --registry=https://registry.npm.taobao.org --no-proxy

来自:phantomjs被墙解决办法

如果中文显示不出来的话说明没有安装对应的字体,debian/ubuntu 可以安装 xfonts-wqy, centos 的话可以安装 wqy-bitmapfont (需下载)或者 bitmap -fonts 和 bitmap-fonts-cjk,安装完之后中文应该就可以正常显示了。

安装 xfonts-wqy 命令:

sudo apt-get install xfonts-wqy

使用PhantomJS截图

这里有官方DEMO

https://raw.github.com/ariya/phantomjs/master/examples/rasterize.js
phantomjs rasterize.js https://www.janecc.com janecc.png

我司,需要根据画谱id来执行,这里用到nodejs](https://janecc.com/tag/nodejs/ "查看关于 nodejs 的相关文章")的子进程调用shell命令

var process = require('child_process')
function onShell(id) {
    var shell = 'phantomjs ./rasterize.js https://img1.ixu.me/page/' + id ./public/upload/' + id + '.png'
    return new Promise(function(resolve, reject) {
        process.exec(shell, function(error, stdout, stderr) {
            console.log(error);
            if (error !== null) { //当成功时,error 会是 null
                console.log('exec error: ' + error);
                reject()
            }
            resolve()
            console.log('stdout:' + stdout);
            console.log('stderr:' + stderr);
        });
    })
}

上线

上线后用PM2来监控进程,最后通过nginx代理服务端口

我司生成快照思路

根据检测画谱修改时间>快照生成时间,就会更新快照,最后通过express的路由生成接口提供给IOS图片链接

版权声明:Shire 发表于 2017-3-30
转载请注明: 使用PhantomJS实现网页快照 | Shire

评论

  1. 2     Windows 7 /    QQ浏览器

    :oops: :o :o :o :o :o 汉字

    广东省东莞市 回复

该文章已经关闭评论