溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么用vue實(shí)現(xiàn)網(wǎng)頁(yè)截圖

發(fā)布時(shí)間:2021-11-17 14:28:02 來(lái)源:億速云 閱讀:454 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)怎么用vue實(shí)現(xiàn)網(wǎng)頁(yè)截圖的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

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

// 頁(yè)面元素轉(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)頁(yè)中可以直接創(chuàng)建一個(gè) a 標(biāo)簽直接下載 
            let a = document.createElement('a')
            a.href = url
            a.download = '首頁(yè)截圖'
            a.click()
        },

別忘了給頁(yè)面所在截圖范圍內(nèi)的父級(jí)添加ref屬性,方便canvas找到父級(jí)計(jì)算寬高從而截屏

怎么用vue實(shí)現(xiàn)網(wǎng)頁(yè)截圖

這就是截圖出來(lái)的效果:

怎么用vue實(shí)現(xiàn)網(wǎng)頁(yè)截圖 

感謝各位的閱讀!關(guān)于“怎么用vue實(shí)現(xiàn)網(wǎng)頁(yè)截圖”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI