使用html2canvas库实现网页截屏的功能

记录一下vue项目使用html2canvas库实现网页截屏的功能,减少以后引用少走弯路。旨在记录,不足之处请多多指教。

1、安装html2canvas库

npm install html2canvas --save

2、在需要截图的Vue组件中引入html2canvas库:

import html2canvas from 'html2canvas'

3、实现截图功能

在需要截图的HTML结构部分添加一个 canvas 元素,给它一个class/ref/id都可,待会要能获取到DOM节点:

<template>
  <div>
    <button @click="capture">截图</button>
    <canvas class="canvas">
    <!-- 需要截图的部分 -->
    ...
    </canvas>
  </div>
</template>

自己定义一个方法,使用html2canvas库将需要截图的元素转换为Canvas,并将生成的图片绘制到canvas元素上:

    // 使用 html2canvas 库将需要截图的元素转换为 Canvas,
    // 并将生成的图片绘制到 canvas 元素上
    capture() {
      // 获取需要截图的元素,这里选择了canvas部分
      const targetElement = document.querySelector('.canvas');
      // 使用html2canvas生成截图,并将结果保存到变量screenshot中
      html2canvas(targetElement, {
        useCORS: true, // 使用跨域资源共享(CORS)
	    scrollX: 0, // 截图时x轴滚动条的位置
	    scrollY: -window.scrollY // 截图时y轴滚动条的位置
      }).then(canvas => {
      // 将截图转为png格式的base64编码,并保存到screenshot变量中
        this.screenshot = canvas.toDataURL('image/png');
        // 将截图转为blob对象,并保存到screenshotBlob变量中
        this.screenshotBlob = canvas.toBlob((blob)=>{
            this.screenshotBlob=blob;
            this.upload()//这里将截图转为blob对象,并保存到screenshotBlob变量中,并通过回调函数在控制台输出blob对象并上传至服务器
        });
      })
    },

**注意:**需要把截图上传至服务器需要将截图转为blob对象,并把请求头以下类型加上

headers: { 'Content-Type': 'multipart/form-data;'}

4、 效果图:

html2canvas截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你怎么在吐泡泡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值