當(dāng)你使用html2canvas對(duì)某個(gè)節(jié)點(diǎn)進(jìn)行截圖時(shí),項(xiàng)目小dom節(jié)點(diǎn)少那還沒什么性能問題,如果是個(gè)大項(xiàng)目,有成百上千個(gè)dom節(jié)點(diǎn),那將是非常頭疼的事情(產(chǎn)品經(jīng)理:小張啊,你這個(gè)截圖功能為什么需要這個(gè)長(zhǎng)的時(shí)間,這讓客戶怎么用,重新改。小張:********...)。不多bb了,直接開始
?
html2canvas的配置項(xiàng)提供了一個(gè)回調(diào)函數(shù)?ignoreElements, 他的作用就是過濾節(jié)點(diǎn)的, html2canvas 他會(huì)對(duì)你的dom樹進(jìn)行循環(huán),每次循環(huán)都會(huì)調(diào)用一次 ignoreElements,ignoreElements接收一個(gè)參數(shù)就是當(dāng)前循環(huán)到的dom , 當(dāng)你返回true就不會(huì)循環(huán)這個(gè)節(jié)點(diǎn)的子節(jié)點(diǎn)了,意思就是過濾了當(dāng)前節(jié)點(diǎn),反之則保留當(dāng)前節(jié)點(diǎn)繼續(xù)向下循環(huán)。
?
代碼:文章來源:http://www.zghlxwxcb.cn/news/detail-524944.html
1 function getImages(element){ 2 const canvas = await html2canvas(element, { 3 allowTaint: false, 4 // 因?yàn)閌allowTaint`表示是否允許被污染,而被污染的canvas是沒法使用`toDataURL()`轉(zhuǎn)`base64`流的,但是我們這需要`base64`,所有`allowTaint`需要被設(shè)置為`false` 5 useCORS: true, // 允許跨域 6 tainttest: true, // 檢測(cè)每張圖片都已經(jīng)加載完成 7 logging: true, 8 ignoreElements:(e)=>{ 9 if(e.contains(element) || element.contains(e) || e.getAttribute('data-html2canvas') != null){ 10 return false 11 } 12 return true 13 }, 14 backgroundColor: `rgb(255,255,255)`, // 轉(zhuǎn)換圖片可能會(huì)有白色底色,你可根據(jù)你的頁面或者PM要求設(shè)置一下背景色,不要的話就null 15 }) 16 17 let imgUrl = canvas.toDataURL("image/jpeg"); 18 if(imgUrl == 'data:,') return '' 19 console.log(imgUrl); 20 return imgUrl 21 }
element 指的是截取的目標(biāo)節(jié)點(diǎn)
e.contains(element) || element.contains(e) 的意思是當(dāng)前循環(huán)的節(jié)點(diǎn)是目標(biāo)節(jié)點(diǎn)的父級(jí)或子急級(jí),直接一步到位, 速度直接提升80%,可以直接拿去甩到產(chǎn)品經(jīng)理的臉上,他還會(huì)夸你nb。嗯,爽不爽?。?!
e.getAttribute('data-html2canvas') != null 這個(gè)就是在節(jié)點(diǎn)上加了一個(gè) data-html2canvas 屬性,若第3行和第7行
1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head data-html2canvas> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width,initial- 7 <link data-html2canvas rel="stylesheet" href="css.css" > 8 </head> 9 <body> 10 <noscript> 11 <strong>We're sorry but api-gateway-admin-front doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> 12 </noscript> 13 <div id="app"></div> 14 </body> 15 </html>
過濾的時(shí)這個(gè)css也會(huì)保留
?文章來源地址http://www.zghlxwxcb.cn/news/detail-524944.html
到了這里,關(guān)于vue使用html2canvas優(yōu)化---節(jié)點(diǎn)過濾的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!