前端页面截屏功能

一、最近项目中需要使用页面截屏功能,通过网上查找资料发现了 dom-to-image 和 html2canvas 两个插件,在经过demo测试验证后,最终选择了hmtl2canvas。

      接下来,我来分享下使用经验~

1. dom-to-image, 参考地址:https://gitee.com/hellocrab_admin/dom-to-image#rendering-options

 安装方法 :

npm install dom-to-image

使用方法:

domtoimage.toPng(document.body, {bgcolor: 'white'})
        .then(function (dataUrl) {
            resolve(dataUrl);
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
            reject()
        });

优点:简单好用,截图比较完整

缺点:对于跨域图片无法解决

 2. html2canvas, 参考地址:https://html2canvas.hertzen.com/

安装方法:

npm install --save html2canvas

使用方法:

复制代码
html2canvas(document.body, {
            allowTaint: true,
            // scale: 5,
            // proxy: ["https://lupic.cdn.bcebos.com", "https://img1.baidu.com"],
            // proxy:  "https://img1.baidu.com",
            proxy:  proxyUrl,
            useCORS: true,
            foreignObjectRendering: true,
            width:1000,
            height: 500,
            x: 0,
            // y:0
        }).then(function(canvas) {
            let url = canvas.toDataURL("image/png");
            resolve(url);
        });
复制代码

 优点:简单好用,可解决跨域内容

 缺点:截图完整性稍微有点差

3. 通过快捷键截图

  

复制代码
// 添加keydown事件监听器
    document.addEventListener('keydown', (event) => {
      console.log('keydown', event.code)
      // 将按下的键存入keysPressed数组
      if (!this.keysPressed.includes(event.code)) {
        this.keysPressed.push(event.code)
        // 如果同时按下了'KeyS'和'KeyR'两个键,则触发相应操作
        if (this.keysPressed.indexOf('KeyS') !== -1 && this.keysPressed.indexOf('KeyR') !== -1) {
          // console.log('domtoimage', domtoimage, document.body)
          this.screenPic()

          // 清空已经按下的键列表
          this.keysPressed = []
        }
      }
    })
复制代码

 

posted @   张哲Zeo  阅读(483)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示