Vue2 html2canvas实现截图

1. 安装html2canvas
npm i html2canvas -S
2. ref 绑定截图区域
<template>
  <div class="save-container box clmcenter">
    
    <div class="savebox clmstart" ref="cutBox" v-show="!imgshow">
      <img src="../assets/img/logo2.png" class="sylogo2">
      <img :src="usercutimg" class="usercutimg" @load="cutimgloaded">
    div>
    
    <img :src="finalImg" class="finalimg" v-show="imgshow">    
    <p class="savetip">长按图片保存p>
  div>
template>
3. 截图
<script>
import { Toast } from "vant";
import html2canvas from "html2canvas";
export default {
  data () {
    return {
      usercutimg: null,
      finalImg: null,
      imgshow: false,
    }
  },
  mounted () {
    this.usercutimg = this.$store.state.userimgH    
  },
  methods: {
    // 用户上传的图片加载完成后执行截图
    cutimgloaded () {
      this.$nextTick(() => {
        this.cutPicture(this.$refs.cutBox)
      })
    },
    //截图方法
    cutPicture (cutbox) {
      // 等待提示
      Toast.loading({
        message: "照片合成中,请稍后...",
        forbidClick: true,
        duration: 0, //值为 0 时,toast 不会消失
        overlay: true, //是否显示背景遮罩层
      });
      const shareContent = cutbox;
      const width = shareContent.offsetWidth;
      const height = shareContent.offsetHeight;
      const canvas = document.createElement("canvas");
      const scale = 2;
      // 宽高扩大 2 倍 处理图片模糊
      canvas.width = width * scale;
      canvas.height = height * scale;
      canvas.getContext("2d").scale(scale, scale);
      const options = {
        width: width,
        height: height,
        canvas: canvas,
        useCORS: true,
        logging: true,
        scale: 1,
        dpi: 300,
      };
      html2canvas(shareContent, options).then((canvas) => {
        const context = canvas.getContext("2d");
        context.scale(scale, scale)
        context.mozImageSmoothingEnabled = false;
        context.webkitImageSmoothingEnabled = false;
        context.msImageSmoothingEnabled = false;
        context.imageSmoothingEnabled = false;
        // 生成图片地址
        const imgUrl = canvas.toDataURL();
        this.finalImg = imgUrl;
        this.imgshow = true
        // 清除提示
        Toast.clear()
      });
    },
  }
}
</script>

3. 样式部分

你可能感兴趣的:(vue,js,javascript,前端,html)