html2canvas给指定区域添加满屏水印

效果图如下:

html2canvas给指定区域添加满屏水印_第1张图片

直接贴上代码

下载插件: npm i html2canvas

<template>
  <div ref="imageDom">
    <el-button @click="downloadPicture">下载el-button>
    <div>
      <el-table
        class="tableX"
        :height="flag ? '400' : ''"
        :data="tableData"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          :fixed="flag ? true : false"
          prop="date"
          label="日期"
          width="180"
        >
        el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        el-table-column>
        <el-table-column prop="address" label="地址"> el-table-column>
        <el-table-column prop="age" label="年龄"> el-table-column>
        <el-table-column prop="sex" label="性别"> el-table-column>
        <el-table-column prop="hobby" label="爱好"> el-table-column>
      el-table>
    div>
  div>
template>

<script>
//下载插件 npm i html2canvas
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      //模拟数据
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "开始",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市",
        },
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市",
        },
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市",
        },
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市",
        },
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海",
          age: 30,
          sex: "女",
          hobby: "爱好",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "结尾",
        },
      ],
      h: 400,
      flag: true,
      wmConfig: {
        font: "microsoft yahei", //字体
        textArray: ["xixi", "嘻嘻"], //水印文本内容,允许数组最大长度3 即:3行水印
        density: 4, //密度 建议取值范围1-5   值越大,水印越多,可能会导致水印重叠等问题,请慎重!!!
      },
    };
  },
  mounted() {
  },
  methods: {
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 0) {
        return "warning-row";
      } else if (rowIndex % 2 !== 0) {
        return "success-row";
      }
      return "";
    },
    //截图
    downloadPicture() {
      this.flag = false;
      this.$nextTick(() => {
        var width = this.$refs.imageDom.style.width;
        var cloneDom = this.$refs.imageDom.cloneNode(true);
        cloneDom.style.position = "absolute";
        cloneDom.style.top = "0px";
        cloneDom.style.zIndex = "-1";
        cloneDom.style.width = width;
        console.log(cloneDom);
        document.body.appendChild(cloneDom);
        html2canvas(cloneDom).then(async(canvas) => {
          // 转成图片,生成图片地址
          var imgUrl = canvas.toDataURL("image/png");
          let resultBase64 = await this.base64AddWaterMaker(imgUrl, this.wmConfig);
          console.log(resultBase64);
          imgUrl = resultBase64;
          var eleLink = document.createElement("a");
          eleLink.href = imgUrl; // 转换后的图片地址
          eleLink.download = "pictureName";
          // 触发点击
          document.body.appendChild(eleLink);
          eleLink.click();
          // 然后移除
          document.body.removeChild(eleLink);
        });
        cloneDom.style.display = "none";
        this.flag = true;
      });
    },
    //画布添加水印
    drawWaterMark(ctx, imgWidth, imgHeight, wmConfig) {
      let fontSize;
      if (imgWidth >= 3456) {
        fontSize = 50;
      } else if (imgWidth >= 2700) {
        fontSize = 30;
      } else if (imgWidth >= 2000) {
        fontSize = 26;
      } else if (imgWidth >= 1436) {
        fontSize = 20;
      } else if (imgWidth >= 800) {
        fontSize = 12;
      } else if (imgWidth >= 500) {
        fontSize = 10;
      } else {
        fontSize = 8;
      }
      console.log(imgWidth, imgHeight, fontSize);
      ctx.font = `${fontSize}px ${wmConfig.font}`;
      ctx.lineWidth = 1;
      ctx.fillStyle = "rgba(0,0,0,0.5)";  //根据页面的背景色来设置水印颜色
      ctx.textAlign = "left";
      ctx.textBaseline = "middle";

      //文字坐标
      const maxPx = Math.max(imgWidth, imgHeight);
      const stepPx = Math.floor(maxPx / wmConfig.density);
      let arrayX = [0]; //初始水印位置 canvas坐标 0 0 点
      while (arrayX[arrayX.length - 1] < maxPx / 2) {
        arrayX.push(arrayX[arrayX.length - 1] + stepPx);
      }
      arrayX.push(
        ...arrayX.slice(1, arrayX.length).map((el) => {
          return -el;
        })
      );

      console.log(arrayX);

      for (let i = 0; i < arrayX.length; i++) {
        for (let j = 0; j < arrayX.length; j++) {
          ctx.save();
          ctx.translate(imgWidth / 2, imgHeight / 2); ///画布旋转原点 移到 图片中心
          ctx.rotate(-Math.PI / 5);
          if (wmConfig.textArray.length > 3) {
            wmConfig.textArray = wmConfig.textArray.slice(0, 3);
          }
          wmConfig.textArray.forEach((el, index) => {
            let offsetY = fontSize * index + 2;
            ctx.fillText(el, arrayX[i], arrayX[j] + offsetY);
          });
          ctx.restore();
        }
      }
    },
    //给base64图片添加水印
    base64AddWaterMaker(base64Img, wmConfig) {
      if (wmConfig.textArray.length === 0) {
        console.error("****没有水印内容*****");
        return base64Img;
      }

      return new Promise((resolve, reject) => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        const img = new Image();
        let resultBase64 = null;
        img.onload =  ()=> {
          canvas.width = img.width;
          canvas.height = img.height;
          console.log(img.width,img.height);
          //canvas绘制图片,0 0  为左上角坐标原点
          ctx.drawImage(img, 0, 0);
          //写入水印
          this.drawWaterMark(ctx, img.width, img.height, this.wmConfig);
          resultBase64 = canvas.toDataURL("image/png");
          console.log(resultBase64);
          if (!resultBase64) {
            reject();
          } else {
            resolve(resultBase64);
          }
        };
        img.src = base64Img;
      });
    },
  },
};
script>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
style>

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