调整了canvas的高度页面变化后还原_Web 页面录屏实现
(給前端樹加星標(biāo),提升前端技能)
作者:frontdoghttps://juejin.im/post/5c601e2f51882562d029d583寫在前面的話
在看到評(píng)論后,突然意識(shí)到自己沒有提前說明,本文可以說是一篇調(diào)研學(xué)習(xí)文,是我自己感覺可行的一套方案,后續(xù)會(huì)去讀讀已經(jīng)開源的一些類似的代碼庫(kù),補(bǔ)足自己遺漏的一些細(xì)節(jié),所以大家可以當(dāng)作學(xué)習(xí)文,生產(chǎn)環(huán)境慎用。
錄屏重現(xiàn)錯(cuò)誤場(chǎng)景
如果你的應(yīng)用有接入到web apm系統(tǒng)中,那么你可能就知道apm系統(tǒng)能幫你捕獲到頁(yè)面發(fā)生的未捕獲錯(cuò)誤,給出錯(cuò)誤棧,幫助你定位到BUG。但是,有些時(shí)候,當(dāng)你不知道用戶的具體操作時(shí),是沒有辦法重現(xiàn)這個(gè)錯(cuò)誤的,這時(shí)候,如果有操作錄屏,你就可以清楚地了解到用戶的操作路徑,從而復(fù)現(xiàn)這個(gè)BUG并且修復(fù)。
實(shí)現(xiàn)思路
思路一:利用Canvas截圖
這個(gè)思路比較簡(jiǎn)單,就是利用canvas去畫網(wǎng)頁(yè)內(nèi)容,比較有名的庫(kù)有:html2canvas,這個(gè)庫(kù)的簡(jiǎn)單原理是:
這個(gè)實(shí)現(xiàn)是比較復(fù)雜的,但是我們可以直接使用,所以我們可以獲取到我們想要的網(wǎng)頁(yè)截圖。
為了使得生成的視頻較為流暢,我們一秒中需要生成大約25幀,也就是需要25張截圖,思路流程圖如下:
但是,這個(gè)思路有個(gè)最致命的不足:為了視頻流暢,一秒中我們需要25張圖,一張圖300KB,當(dāng)我們需要30秒的視頻時(shí),圖的大小總共為220M,這么大的網(wǎng)絡(luò)開銷明顯不行。
思路二:記錄所有操作重現(xiàn)
為了降低網(wǎng)絡(luò)開銷,我們換個(gè)思路,我們?cè)谧铋_始的頁(yè)面基礎(chǔ)上,記錄下一步步操作,在我們需要"播放"的時(shí)候,按照順序應(yīng)用這些操作,這樣我們就能看到頁(yè)面的變化了。這個(gè)思路把鼠標(biāo)操作和DOM變化分開:
鼠標(biāo)變化:
DOM變化:
當(dāng)然這個(gè)說明是比較簡(jiǎn)略的,鼠標(biāo)的記錄比較簡(jiǎn)單,我們不展開講,主要說明一下DOM監(jiān)控的實(shí)現(xiàn)思路。
頁(yè)面首次全量快照
首先你可能會(huì)想到,要實(shí)現(xiàn)頁(yè)面全量快照,可以直接使用outerHTML
const content = document.documentElement.outerHTML;這樣就簡(jiǎn)單記錄了頁(yè)面的所有DOM,你只需要首先給DOM增加標(biāo)記id,然后得到outerHTML,然后去除JS腳本。
但是,這里有個(gè)問題,使用outerHTML記錄的DOM會(huì)將把臨近的兩個(gè)TextNode合并為一個(gè)節(jié)點(diǎn),而我們后續(xù)監(jiān)控DOM變化時(shí)會(huì)使用MutationObserver,此時(shí)你需要大量的處理來兼容這種TextNode的合并,不然你在還原操作的時(shí)候無法定位到操作的目標(biāo)節(jié)點(diǎn)。
那么,我們有辦法保持頁(yè)面DOM的原有結(jié)構(gòu)嗎?
答案是肯定的,在這里我們使用Virtual DOM來記錄DOM結(jié)構(gòu),把documentElement變成Virtual DOM,記錄下來,后面還原的時(shí)候重新生成DOM即可。
DOM轉(zhuǎn)化為Virtual DOM
我們?cè)谶@里只需要關(guān)心兩種Node類型:Node.TEXT_NODE和Node.ELEMENT_NODE。同時(shí),要注意,SVG和SVG子元素的創(chuàng)建需要使用API:createElementNS,所以,我們?cè)谟涗沄irtual DOM的時(shí)候,需要注意namespace的記錄,上代碼:
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; const XML_NAMESPACES = ['xmlns', 'xmlns:svg', 'xmlns:xlink'];function createVirtualDom(element, isSVG = false) {switch (element.nodeType) {case Node.TEXT_NODE:return createVirtualText(element);case Node.ELEMENT_NODE:return createVirtualElement(element, isSVG || element.tagName.toLowerCase() === 'svg');default:return null;} }function createVirtualText(element) {const vText = {text: element.nodeValue,type: 'VirtualText',};if (typeof element.__flow !== 'undefined') {vText.__flow = element.__flow;}return vText; }function createVirtualElement(element, isSVG = false) {const tagName = element.tagName.toLowerCase();const children = getNodeChildren(element, isSVG);const { attr, namespace } = getNodeAttributes(element, isSVG);const vElement = {tagName, type: 'VirtualElement', children, attributes: attr, namespace,};if (typeof element.__flow !== 'undefined') {vElement.__flow = element.__flow;}return vElement; }function getNodeChildren(element, isSVG = false) {const childNodes = element.childNodes ? [...element.childNodes] : [];const children = [];childNodes.forEach((cnode) => {children.push(createVirtualDom(cnode, isSVG));});return children.filter(c => !!c); }function getNodeAttributes(element, isSVG = false) {const attributes = element.attributes ? [...element.attributes] : [];const attr = {};let namespace;attributes.forEach(({ nodeName, nodeValue }) => {attr[nodeName] = nodeValue;if (XML_NAMESPACES.includes(nodeName)) {namespace = nodeValue;} else if (isSVG) {namespace = SVG_NAMESPACE;}});return { attr, namespace }; }通過以上代碼,我們可以將整個(gè)documentElement轉(zhuǎn)化為Virtual DOM,其中__flow用來記錄一些參數(shù),包括標(biāo)記ID等,Virtual Node記錄了:type、attributes、children、namespace。
Virtual DOM還原為DOM
將Virtual DOM還原為DOM的時(shí)候就比較簡(jiǎn)單了,只需要遞歸創(chuàng)建DOM即可,其中nodeFilter是為了過濾script元素,因?yàn)槲覀儾恍枰狫S腳本的執(zhí)行。
DOM結(jié)構(gòu)變化監(jiān)控
在這里,我們使用了API:MutationObserver,更值得高興的是,這個(gè)API是所有瀏覽器都兼容的,所以我們可以大膽使用。
使用MutationObserver:
const options = {childList: true, // 是否觀察子節(jié)點(diǎn)的變動(dòng)subtree: true, // 是否觀察所有后代節(jié)點(diǎn)的變動(dòng)attributes: true, // 是否觀察屬性的變動(dòng)attributeOldValue: true, // 是否觀察屬性的變動(dòng)的舊值characterData: true, // 是否節(jié)點(diǎn)內(nèi)容或節(jié)點(diǎn)文本的變動(dòng)characterDataOldValue: true, // 是否節(jié)點(diǎn)內(nèi)容或節(jié)點(diǎn)文本的變動(dòng)的舊值// attributeFilter: ['class', 'src'] 不在此數(shù)組中的屬性變化時(shí)將被忽略 };const observer = new MutationObserver((mutationList) => {// mutationList: array of mutation }); observer.observe(document.documentElement, options);使用起來很簡(jiǎn)單,你只需要指定一個(gè)根節(jié)點(diǎn)和需要監(jiān)控的一些選項(xiàng),那么當(dāng)DOM變化時(shí),在callback函數(shù)中就會(huì)有一個(gè)mutationList,這是一個(gè)DOM的變化列表,其中mutation的結(jié)構(gòu)大概為:
{type: 'childList', // or characterData、attributestarget: <DOM>,// other params }我們使用一個(gè)數(shù)組來存放mutation,具體的callback為:
const onMutationChange = (mutationsList) => {const getFlowId = (node) => {if (node) {// 新插入的DOM沒有標(biāo)記,所以這里需要兼容if (!node.__flow) node.__flow = { id: uuid() };return node.__flow.id;}};mutationsList.forEach((mutation) => {const { target, type, attributeName } = mutation;const record = { type, target: getFlowId(target), };switch (type) {case 'characterData':record.value = target.nodeValue;break;case 'attributes':record.attributeName = attributeName;record.attributeValue = target.getAttribute(attributeName);break;case 'childList':record.removedNodes = [...mutation.removedNodes].map(n => getFlowId(n));record.addedNodes = [...mutation.addedNodes].map((n) => {const snapshot = this.takeSnapshot(n);return {...snapshot,nextSibling: getFlowId(n.nextSibling),previousSibling: getFlowId(n.previousSibling)};});break;}this.records.push(record);}); }function takeSnapshot(node, options = {}) {this.markNodes(node);const snapshot = {vdom: createVirtualDom(node),};if (options.doctype === true) {snapshot.doctype = document.doctype.name;snapshot.clientWidth = document.body.clientWidth;snapshot.clientHeight = document.body.clientHeight;}return snapshot; }這里面只需要注意,當(dāng)你處理新增DOM的時(shí)候,你需要一次增量的快照,這里仍然使用Virtual DOM來記錄,在后面播放的時(shí)候,仍然生成DOM,插入到父元素即可,所以這里需要參照DOM,也就是兄弟節(jié)點(diǎn)。
表單元素監(jiān)控
上面的MutationObserver并不能監(jiān)控到input等元素的值變化,所以我們需要對(duì)表單元素的值進(jìn)行特殊處理。
oninput事件監(jiān)聽
MDN文檔:http://developer.mozilla.org/en-US/docs/…
事件對(duì)象:select、input,textarea
window.addEventListener('input', this.onFormInput, true);onFormInput = (event) => {const target = event.target;if (target && target.__flow &&['select', 'textarea', 'input'].includes(target.tagName.toLowerCase())) {this.records.push({type: 'input', target: target.__flow.id, value: target.value, });} }在window上使用捕獲來捕獲事件,后面也是這樣處理的,這樣做的原因是我們是可能并經(jīng)常在冒泡階段阻止冒泡來實(shí)現(xiàn)一些功能,所以使用捕獲可以減少事件丟失,另外,像scroll事件是不會(huì)冒泡的,必須使用捕獲。
onchange事件監(jiān)聽
MDN文檔:http://developer.mozilla.org/en-US/docs/…
input事件沒法滿足type為checkbox和radio的監(jiān)控,所以需要借助onchange事件來監(jiān)控
window.addEventListener('change', this.onFormChange, true);onFormChange = (event) => {const target = event.target;if (target && target.__flow) {if (target.tagName.toLowerCase() === 'input' &&['checkbox', 'radio'].includes(target.getAttribute('type'))) {this.records.push({type: 'checked', target: target.__flow.id, checked: target.checked,});}} }onfocus事件監(jiān)聽
MDN文檔:http://developer.mozilla.org/en-US/docs/…
onblur事件監(jiān)聽
MDN文檔:http://developer.mozilla.org/en-US/docs/…
window.addEventListener('blur', this.onFormBlur, true);onFormBlur = (event) => {const target = event.target;if (target && target.__flow) {this.records.push({type: 'blur', target: target.__flow.id,});} }媒體元素變化監(jiān)聽
這里指audio和video,類似上面的表單元素,可以監(jiān)聽onplay、onpause事件、timeupdate、volumechange等等事件,然后存入records
Canvas畫布變化監(jiān)聽
canvas內(nèi)容變化沒有拋出事件,所以我們可以:
canvas監(jiān)聽研究沒有很深入,需要進(jìn)一步深入研究
播放
思路比較簡(jiǎn)單,就是從后端拿到一些信息:
利用這些信息,你就可以首先生成頁(yè)面DOM,其中包括過濾script標(biāo)簽,然后創(chuàng)建iframe,append到一個(gè)容器中,其中使用一個(gè)map來存儲(chǔ)DOM
function play(options = {}) {const { container, records = [], snapshot ={} } = options;const { vdom, doctype, clientHeight, clientWidth } = snapshot;this.nodeCache = {};this.records = records;this.container = container;this.snapshot = snapshot;this.iframe = document.createElement('iframe');const documentElement = createElement(vdom, (node) => {// 緩存DOMconst flowId = node.__flow && node.__flow.id;if (flowId) {this.nodeCache[flowId] = node;}// 過濾scriptreturn !(node.nodeType === Node.ELEMENT_NODE && node.tagName.toLowerCase() === 'script'); });this.iframe.style.width = `${clientWidth}px`;this.iframe.style.height = `${clientHeight}px`;container.appendChild(iframe);const doc = iframe.contentDocument;this.iframeDocument = doc;doc.open();doc.write(`<!doctype ${doctype}><html><head></head><body></body></html>`);doc.close();doc.replaceChild(documentElement, doc.documentElement);this.execRecords(); }function execRecords(preDuration = 0) {const record = this.records.shift();let node;if (record) {setTimeout(() => {switch (record.type) {// 'childList'、'characterData'、// 'attributes'、'input'、'checked'、// 'focus'、'blur'、'play''pause'等事件的處理}this.execRecords(record.duration);}, record.duration - preDuration)} }上面的duration在上文中省略了,這個(gè)你可以根據(jù)自己的優(yōu)化來做播放的流暢度,看是多個(gè)record作為一幀還是原本呈現(xiàn)。
覺得本文對(duì)你有幫助?請(qǐng)分享給更多人
關(guān)注「前端樹」加星標(biāo),提升前端技能
喜歡就點(diǎn)一下「好看」唄~
總結(jié)
以上是生活随笔為你收集整理的调整了canvas的高度页面变化后还原_Web 页面录屏实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NOI数据结构:树套树
- 下一篇: eigen冲突 sophus 安装_SL