vue页面全局添加水印

水印效果如图:vue页面全局添加水印_第1张图片
添加水印方法:
watermarker.js 引入到src/common里

import moment from "moment";

let watermark = {}

let setWatermark = (str1) => {
  let id = '1.23452384164.123412415'
  // let str2 = moment(new Date()).format("YYYY-MM-DD");

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }

  let can = document.createElement('canvas')
  can.width = 230
  can.height = 120

  let cans = can.getContext('2d')
  cans.rotate(-20 * Math.PI / 180)
  cans.font = '15px Vedana'
  cans.fillStyle = '#666666'
  cans.textAlign = 'center'
  cans.textBaseline = 'Middle'
  cans.fillText(str1, can.width / 2, can.height) // 水印在画布的位置x,y轴
  // cans.fillText(str2, can.width / 2, can.height + 22)

  let div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '0px'
  div.style.left = '0px'
  div.style.opacity = '0.15'
  div.style.position = 'fixed'
  div.style.zIndex = '100000'
  div.style.width = document.documentElement.clientWidth + 'px'
  div.style.height = document.documentElement.clientHeight  + 'px'
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  document.body.appendChild(div)
  return id
}

// 该方法只允许调用一次
watermark.set = (str) => {
  let id = setWatermark(str)
  setInterval(() => {
    if (document.getElementById(id) === null) {
      id = setWatermark(str)
    }
  }, 500)
  window.onresize = () => {
    setWatermark(str)
  }
}

export default watermark;

在需要添加水印的模块的APP.vue入口文件引入watermark.js

import watermark from "../../common/watermarker";
  export default {
    mounted(){
      this.setWatermark();
    },
    methods:{
      setWatermark() {
        this.axios.business
        .get("/dosp/templateMaintain/getWatermark", '',"dospManager")
        .then(res => {
            let watermark_txt = res.data ;
            watermark.set(watermark_txt)
        })
      },
    }
  };

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