欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js實(shí)現(xiàn)網(wǎng)頁截圖的兩種方案詳析

 更新時(shí)間:2025年06月16日 10:40:17   作者:樹上的  
在Web開發(fā)中,實(shí)現(xiàn)網(wǎng)頁截圖功能可以幫助我們保存網(wǎng)頁內(nèi)容、生成海報(bào)、制作截圖分享等,這篇文章主要介紹了js實(shí)現(xiàn)網(wǎng)頁截圖的兩種方案,需要的朋友可以參考下

方案一:使用 html2canvas 庫(推薦)

原理:將 HTML DOM 元素轉(zhuǎn)換為 Canvas,再導(dǎo)出為圖片

特點(diǎn):兼容性好,支持大部分現(xiàn)代瀏覽器,但需注意 CSS 屬性兼容性

實(shí)現(xiàn)步驟:

1.安裝依賴:

npm install html2canvas

2.基礎(chǔ)截圖代碼:

import html2canvas from "html2canvas"

//截取整個(gè)屏幕
 const screenFn = () => {
    const element = document.body
    html2canvas(element).then((canvas) => {
        const imgUrl = canvas.toDataURL("image/png")
        const link = document.createElement("a")
        link.download = "screenshot.png"
        link.href = imgUrl
        link.click()
    })
 }

//截取特定元素
const screenFn = () => {
    const element = document.getElementById("version")
    if (element) {
        html2canvas(element, {
          allowTaint: true, // 允許跨域圖片
          useCORS: true, // 使用 CORS 加載圖片
          scale: 2, // 提升截圖分辨率
          logging: true, // 調(diào)試時(shí)查看日志
          scrollY: -window.scrollY // 處理滾動(dòng)位置
        }).then((canvas) => {
          const imgUrl = canvas.toDataURL("image/png")
          const link = document.createElement("a")
          link.download = "screenshot.png"
          link.href = imgUrl
          link.click()
        })
    }
}

方案二: 使用原生 API Window: getDisplayMedia()

原理:通過屏幕共享 API 捕獲當(dāng)前標(biāo)簽頁

特點(diǎn):需用戶授權(quán),適合需要交互式操作的場景

實(shí)現(xiàn)步驟:

const screenFn = async () => {
    try {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: { displaySurface: "browser" }
        })
        const videoTrack = stream.getVideoTracks()[0]
        const imageCapture = new ImageCapture(videoTrack)
        const bitmap = await imageCapture.grabFrame()

        // 將 bitmap 繪制到 canvas
        const canvas = document.createElement("canvas")
        canvas.width = bitmap.width
        canvas.height = bitmap.height
        const ctx = canvas.getContext("2d")
        ctx.drawImage(bitmap, 0, 0)

        // 導(dǎo)出圖片
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob)
          const a = document.createElement("a")
          a.href = url
          a.download = "screenshot.png"
          a.click()
        }, "image/png")

        videoTrack.stop()
    } catch (err) {
        console.error("截圖失敗:", err)
    }
}

兩種方案優(yōu)缺點(diǎn):

1.方案一:html2canvas

優(yōu)點(diǎn):純前端實(shí)現(xiàn),靈活度高

缺點(diǎn):復(fù)雜頁面渲染可能有差異

2.方案二:getDisplayMedia

優(yōu)點(diǎn):原生 API,無需額外依賴

缺點(diǎn):需要用戶手動(dòng)選擇分享區(qū)域

總結(jié)

到此這篇關(guān)于js實(shí)現(xiàn)網(wǎng)頁截圖的文章就介紹到這了,更多相關(guān)js網(wǎng)頁截圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論