最近研究了下如何利用JavaScript實現網頁截屏,包括在瀏覽器運行的JS,以及在後臺運行的nodeJs的方法。主要看了如下幾個:html
測試的網頁使用了WebGL技術,因此下面的總結會和WebGL相關。前端
無界面瀏覽器,多用於網頁自動化測試、網頁截屏、網頁的網絡監控等。node
PhantomJS是能夠經過JS進行編程的headless瀏覽器,使用的是QtWebKit內核。git
實現截屏的代碼,假設文件名爲github.js:github
// 建立一個網頁實例 var page = require('webpage').create(); // 加載頁面 page.open('http://github.com/', function () { // 給網頁截屏,保存到github.png文件中 page.render('github.png'); phantom.exit(); })
運行:web
phantomjs github.js
普通的頁面沒有問題,可是若是運行包含WebGL的頁面,發現截屏不對。通過一些調查,發現不支持WebGL,github issue。chrome
總結:npm
Puppeteer是一個Node庫,提供了控制chrome和chromium的API。默認運行headless模式,也支持界面運行。編程
實現截屏的代碼example.js:canvas
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setViewport({ // 設置視窗大小 width: 600, height: 800 }); await page.goto('https://example.com'); // 打開頁面 await page.screenshot({path: 'example.png'}); // path: 截屏文件保存路徑 await browser.close(); })();
運行:
node example.js
接下來看下screenshot
方法的實現原理:
screenshot
的源碼位於lib/cjs/puppeteer/common/Page.js
文件中,是一個異步方法:
async screenshot(options = {}) { // ... return this._screenshotTaskQueue.postTask(() => this._screenshotTask(screenshotType, options)); } async _screenshotTask(format, options) { // ... const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip, }); // ... }
這個this._client.send
又是個什麼東西?別急,咱們從新看下Puppeteer的定義:
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol.
看到最後面那個DevTools Protocol了嗎?這是個什麼東西:
The Chrome DevTools Protocol allows for tools to instrument, inspect, debug and profile Chromium, Chrome and other Blink-based browsers.
詳細的解釋能夠看這篇博客。
簡單來講,Puppeteer就是經過WebSocket給瀏覽器發送遵循Chrome Devtools Protocol的數據,命令瀏覽器去執行一些操做。而後,瀏覽器再經過WebSocket把結果返回給Puppeteer。這個過程是異步的,因此看源代碼會發現好多async/await。
因此screenshot
方法是調用了Chrome Devtools Protocol的captureScreenshot。
總結:
SlimerJS和PhantomJS相似。不一樣點是SlimerJS是基於火狐的瀏覽器引擎Gecko,而不是Webkit。
SlimerJS能夠經過npm安裝,最新版本是1.x。不過兼容的火狐版本是53.0到59.0。我看如今火狐最新版本都82了。由於我本機是安裝了火狐最新版本的,因此我還得安裝一個老版本的火狐,好比59.0。能夠參考這篇安裝舊版本的火狐瀏覽器。我是mac系統,感受安裝仍是挺容易的。
實現截屏的代碼screenshot.js:
var page = require('webpage').create(); page.open("http://slimerjs.org", function (status) { page.viewportSize = { width:1024, height:768 }; page.render('screenshot.png'); });
運行
// mac操做系統設置火狐路徑 export SLIMERJSLAUNCHER=/Applications/Firefox.app/Contents/MacOS/firefox ./node_modules/.bin/slimerjs screenshot.js // 我是局部安裝的slimer包
須要注意的是SLIMERJSLAUNCHER=/Applications/Firefox.app/Contents/MacOS/firefox
啓動的是火狐默認的安裝路徑,由於我一開始就有火狐瀏覽器,因此啓動的是最新版本的瀏覽器,而後就報錯了,說不兼容。在前面我安裝過一個59版本的火狐,那麼這個火狐瀏覽器的路徑是什麼?
在應用程序裏面我把這個舊版本的火狐命名爲Firefox59,而後這個路徑就是/Applications/Firefox59.app/Contents/MacOS/firefox
。從新設置SLIMERJSLAUNCHER
爲59版本的火狐瀏覽器以後,發現就能成功了。
不過,Puppeteer默認會打開瀏覽器界面,也就是non-headless模式。若是要使用headless模式,能夠
./node_modules/.bin/slimerjs --headless screenshot.js
不過,headless模式下,不支持WebGL。
我在寫例子的時候,發現的一個明顯的不一樣就是Puppeteer截屏是異步函數,而SlimerJS截屏是同步函數?好奇心驅使下,看了下源碼(src/modules/slimer-sdk/webpage.js):
render: function(filename, options) { // ... let canvas = webpageUtils.getScreenshotCanvas( browser.contentWindow, finalOptions.ratio, finalOptions.onlyViewport, this); } canvas.toBlob(function(blob) { let reader = new browser.contentWindow.FileReader(); reader.onloadend = function() { content = reader.result; } reader.readAsBinaryString(blob); }, finalOptions.contentType, finalOptions.quality); // ... }
webpageUtils.getScreenshotCanvas(src/modules/webpageUtils.jsm):
getScreenshotCanvas : function(window, ratio, onlyViewport, webpage) { // ... // create the canvas let canvas = window.document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight; let ctx = canvas.getContext("2d"); ctx.scale(ratio, ratio); ctx.drawWindow(window, clip.left, clip.top, clip.width, clip.height, "rgba(0,0,0,0)"); ctx.restore(); return canvas; }
關鍵代碼就是那行ctx.drawWindow
。what?JS原生API還支持直接截屏?
CanvasRenderingContext2D.drawWindow():只有火狐支持,已經被廢棄掉的非規範定義的標準API。
總結
dom-to-image:前端截屏的開源庫。工做原理是:
SVG的foreignObject標籤能夠包裹任意的html內容。那麼,爲了渲染一個節點,主要進行了如下步驟:
測試的時候,發現外部資源不能加載,因此簡單的瞭解了後就放棄了。
html2canvas。網上查了下感受有一篇文章寫的挺好的:淺析 js 實現網頁截圖的兩種方式。感興趣的能夠看下。
雖而後面這兩種是前端的實現方式,可是結合前面講的headless庫,也是能夠實現後端截屏的。以Puppeteer的API爲例,能夠首先使用page.addScriptTag(options)
往網頁中添加前端截屏的庫,而後在page.evaluate(pageFunction[, ...args])
中的pageFunction
函數裏面寫相應的截屏代碼就能夠了,由於pageFunction的執行上下文是網頁上下文,因此能夠獲取到document
等對象。
對截屏的一個簡單研究,寫篇博客整理下思路。若是文中有敘述錯誤的地方,歡迎評論留言。