1. 程式人生 > 程式設計 >如何用vue實現網頁截圖你知道嗎

如何用vue實現網頁截圖你知道嗎

目錄
  • 1、安裝html2Canvas
  • 2、在需要的元件中引入
  • 3、編寫一個截圖按鈕
  • 4、呼叫函式toImage
  • 總結

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 = '首頁截圖' http://www.cppcns.com
a.click() },

別忘了給YZpsvBnp頁面所在截圖範圍內的父級新增ref屬性,方www.cppcns.com便canvas找到父級計算寬高從而截圖

如何用vue實現網頁截圖你知道嗎

這就是截圖出來的效果:

如何用vue實現網頁截圖你知道嗎

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注我們的更多內容!