如何用vue實(shí)現(xiàn)網(wǎng)頁截圖你知道嗎
1、安裝html2Canvas
npm install html2canvas --save
2、在需要的vue組件中引入
import html2canvas from "html2canvas";
3、編寫一個(gè)截圖按鈕
<el-button class="button-dalod" size="mini" title="生成圖片" @click="toImage()" icon="el-icon-download"></el-button>
4、調(diào)用函數(shù)toImage
// 頁面元素轉(zhuǎn)圖片 toImage () { // 手動(dòng)創(chuàng)建一個(gè) canvas 標(biāo)簽 const canvas = document.createElement("canvas") // 獲取父標(biāo)簽,意思是這個(gè)標(biāo)簽內(nèi)的 DOM 元素生成圖片 // imageTofile是給截圖范圍內(nèi)的父級(jí)元素自定義的ref名稱 let canvasBox = this.$refs.imageTofile // 獲取父級(jí)的寬高 const width = parseInt(window.getComputedStyle(canvasBox).width) const height = parseInt(window.getComputedStyle(canvasBox).height) // 寬高 * 2 并放大 2 倍 是為了防止圖片模糊 canvas.width = width * 2 canvas.height = height * 2 canvas.style.width = width + 'px' canvas.style.height = height + 'px' const context = canvas.getContext("2d"); context.scale(2, 2); const options = { backgroundColor: null, canvas: canvas, useCORS: true } html2canvas(canvasBox, options).then((canvas) => { // toDataURL 圖片格式轉(zhuǎn)成 base64 let dataURL = canvas.toDataURL("image/png") console.log(dataURL) this.downloadImage(dataURL) }) }, //下載圖片 downloadImage(url) { // 如果是在網(wǎng)頁中可以直接創(chuàng)建一個(gè) a 標(biāo)簽直接下載 let a = document.createElement('a') a.href = url a.download = '首頁截圖' a.click() },
別忘了給頁面所在截圖范圍內(nèi)的父級(jí)添加ref屬性,方便canvas找到父級(jí)計(jì)算寬高從而截屏
這就是截圖出來的效果:
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Vue首屏性能優(yōu)化組件知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理了一篇關(guān)于Vue首屏性能優(yōu)化組件知識(shí)點(diǎn)總結(jié),有需要的朋友們可以跟著學(xué)習(xí)下。2021-11-11vue.js單頁面應(yīng)用實(shí)例的簡(jiǎn)單實(shí)現(xiàn)
本篇文章主要介紹了vue.js單頁面應(yīng)用實(shí)例的簡(jiǎn)單實(shí)現(xiàn),使用單頁應(yīng)用,沒有頁面切換,就沒有白屏阻塞,可以大大提高 H5 的性能,達(dá)到接近原生的流暢體驗(yàn)。2017-04-04cordova+vue+webapp使用html5獲取地理位置的方法
這篇文章主要介紹了2019-07-07vue中全局路由守衛(wèi)中替代this操作(this.$store/this.$vux)
這篇文章主要介紹了vue中全局路由守衛(wèi)中替代this操作(this.$store/this.$vux),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07Ant Design Vue Pro靜態(tài)路由如何改為動(dòng)態(tài)路由
這篇文章主要介紹了Ant Design Vue Pro靜態(tài)路由如何改為動(dòng)態(tài)路由問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10vue+element-ui集成隨機(jī)驗(yàn)證碼+用戶名+密碼的form表單驗(yàn)證功能
在登入頁面,我們往往需要通過輸入驗(yàn)證碼才能進(jìn)行登入,那我們下面就詳講一下在vue項(xiàng)目中如何配合element-ui實(shí)現(xiàn)這個(gè)功能,需要的朋友可以參考下2018-08-08