vue一键截图并上传至后台

 1.安装html2Canvas

npm install html2canvas --save

 2.在需要的vue页面中引入插件

import html2canvas from "html2canvas";

3.设置一个按钮用来截取屏幕

<button type="primary" size="mini" @click="screenshot">一键截图</button>

4.给需要截取的父级元素添加ref属性,用来获取节点让canvas计算截取内容的宽高

<div ref="toImage">这是内容区域</div>

5.执行screenshot方法让截取的部分生成图片

     screenshot() {
        const canvas = document.createElement("canvas");//创建canvas标签
        let canvasItem = this.$refs.toImage;//获取生成图片的标签
        const width = parseInt(window.getComputedStyle(canvasItem).width); // 获取父级元素的宽度
        const height = parseInt(window.getComputedStyle(canvasItem).height);// 获取父级元素的高度
        canvas.width = width * 2; // 宽高放大2倍,防止图片模糊
        canvas.height = height * 2;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        const context = canvas.getContext("2d");
        context.scale(2, 2);
        const options = {
          backgroundColor: null,
          canvas: canvas,
          useCORS: true
        }
        html2canvas(canvasItem, options).then((canvas) => {
          let imageURL = canvas.toDataURL("image/png") //toDataURL图片格式转成 base64
          this.upLoadFile(imageURL)//上传图片到后台
          // this.downloadImage(imageURL)//下载到本地浏览
        })
      },

6.上传前先将base64转换为二进制文件流

base64toFile (imageURL, filename = 'file') {
        let arr = imageURL.split(',')
        let mime = arr[0].match(/:(.*?);/)[1]
        let suffix = mime.split('/')[1]
        let baseStr = atob(arr[1])
        let n = baseStr.length
        let u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = baseStr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
          type: mime
        })
      },

7.上传到后台

    upLoadFile(url){
        const result = this.base64toFile(url);
        let formData = new FormData(); //参数的格式是formData格式的
        formData.append("file", result); //参数
        this.xxx(formData).then((res) => {    //xxx为请求地址
          if (res.data.status == 200){
            this.$message.success({
              message: "截图成功",
              center: true,
              showClose: true,
              duration: 1000,
            });
          } else {
          return this.$message.error({
            message: "截图失败",
            center: true,
            showClose: true,
            duration: 1000,
          });
          }
        })
      },

8.也可以下载到本地

  // 下载到本地
      downloadImage(url) {
        let screenshotImage = document.createElement('a');
        screenshotImage.href = url;
        screenshotImage.download = '网页截图';
        screenshotImage.click();
      },

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值