vue 實現網頁截圖功能詳解

1、安裝html2Canvas

npm install html2canvas --save

2、在需要的vue組件中引入

import html2canvas from "html2canvas";

3、編寫一個截圖按鈕

<el-button class="button-dalod" size="mini" title="生成圖片" @click="toImage()" icon="el-icon-download"></el-button>

4、調用函數toImage

// 頁面元素轉圖片
        toImage () {
            // 手動創建一個 canvas 標簽
            const canvas = document.createElement("canvas")
            // 獲取父標簽,意思是這個標簽內的 DOM 元素生成圖片
            // imageTofile是給截圖范圍內的父級元素自定義的ref名稱
            let canvasBox = this.$refs.imageTofile
            // 獲取父級的寬高
            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 圖片格式轉成 base64
                let dataURL = canvas.toDataURL("image/png")
                console.log(dataURL)
                this.downloadImage(dataURL)
            })
        },
        //下載圖片
        downloadImage(url) {
            // 如果是在網頁中可以直接創建一個 a 標簽直接下載 
            let a = document.createElement('a')
            a.href = url
            a.download = '首頁截圖'
            a.click()
        },

別忘瞭給頁面所在截圖范圍內的父級添加ref屬性,方便canvas找到父級計算寬高從而截屏

這就是截圖出來的效果:

到此這篇關於vue 實現網頁截圖功能詳解的文章就介紹到這瞭,更多相關vue的內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: