js 页面截图三种解决方案

1.html2canvas

npm install html2canvas

// 引入html2canvas库
import html2canvas from 'html2canvas';

// 设置定时器,每隔10秒执行一次截图操作
setInterval(async () => {
  try {
    // 将网页内容转换为canvas元素
    const canvas = await html2canvas(document.body);

    // 将canvas元素转换为图片文件base64
    const img = canvas.toDataURL('image/png');

    // 图片文件img 处理上床后端
    
  } catch (error) {
    console.error('截图失败:', error);
  }
}, 10000);

2、获取屏幕流转为图片

async function screenshot() {  
    // 获取屏幕流  
    const displayMediaOptions = {  
        video: {  
            cursor: "always"  
        }  
    };  
    const stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);  
  
    // 创建一个video元素来播放屏幕流  
    const video = document.createElement('video');  
    video.srcObject = stream;  
    await video.play();  
  
    // 创建一个canvas元素来截屏  
    const canvas = document.createElement('canvas');  
    canvas.width = video.videoWidth;  
    canvas.height = video.videoHeight;  
  
    // 将视频播放的内容绘制到canvas上  
    const context = canvas.getContext('2d');  
    context.drawImage(video, 0, 0, canvas.width, canvas.height);  
  
    // 将canvas内容转换为base64  
    const base64 = canvas.toDataURL();  
  
    // 关闭视频流  
    video.srcObject.getTracks().forEach((track) => track.stop());  
  
    return base64;  
}

3、让使用者在浏览器插件再去调用插件(不推荐)

你可能感兴趣的:(javascript,前端,开发语言)