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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript中Array()數(shù)組函數(shù)詳解
在JavaScript中數(shù)組也是比較常用的對(duì)象之一,數(shù)組是值的有序集合,本篇文章給大家分享Javascript中Array()數(shù)組函數(shù)詳解,需要的朋友可以參考下2015-08-08
js如何實(shí)現(xiàn)設(shè)計(jì)模式中的模板方法
都知道在js中如果定義兩個(gè)相同名稱的方法,前一個(gè)方法就會(huì)被后一個(gè)方法覆蓋掉,使用此特點(diǎn)就可以實(shí)現(xiàn)模板方法,感興趣的朋友可以了解下本文哈2013-07-07
JavaScrip實(shí)現(xiàn)前端文件下載并接收文件流
在前端,處理文件下載通常涉及到接收一個(gè)文件流,本文為大家整理了前端文件下載并接受文件流的一些常見方法,有需要的小伙伴可以參考一下2024-12-12
完美實(shí)現(xiàn)js選項(xiàng)卡切換效果(一)
這篇文章主要為大家詳細(xì)介紹如何完美實(shí)現(xiàn)js選項(xiàng)卡切換效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03
JavaScript實(shí)現(xiàn)簡單的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)簡單的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
純js代碼實(shí)現(xiàn)未知寬高的元素在指定元素中垂直水平居中顯示
本章節(jié)介紹一下如何實(shí)現(xiàn)未知寬高的元素在指定元素下實(shí)現(xiàn)垂直水平居中效果,代碼簡單易懂,需要的朋友可以參考下本文2015-09-09

