vue页面加水印

watermark.js 

'use strict'

const watermark = {}

const setWatermark = (str, display) => {
  const id = '1.23452384164.123412415'

  if (document.getElementById(id) !== null) {
    document.getElementsByClassName('scrollbar-app-main')[0].removeChild(document.getElementById(id))
  }
  const can = document.createElement('canvas')
  can.width = 400
  can.height = 192

  const cans = can.getContext('2d')
  cans.rotate(-15 * Math.PI / 180)
  cans.font = '16px Vedana'
  cans.fillStyle = 'rgba(200, 200, 200, 0.20)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(str, (can.width - 1000) / 100, can.height / 2)

  const div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '100px'
  div.style.left = '300px'
  div.style.position = 'fixed'
  div.style.zIndex = '100'
  div.style.width = document.getElementsByClassName('scrollbar-app-main')[0].clientWidth + 'px'
  div.style.height = document.getElementsByClassName('scrollbar-app-main')[0].clientHeight + 'px'
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  if (!display || display === 'false') {
    div.style.display = 'none'
  }
  document.getElementsByClassName('scrollbar-app-main')[0].appendChild(div)
  return id
}

// 该方法只允许调用一次
watermark.set = (str, display) => {
  if (display) {
    let id = setWatermark(str, display)
    watermark.interval = setInterval(() => {
      if (document.getElementById(id) === null) {
        id = setWatermark(str, display)
      }
    }, 500)
    window.onresize = () => {
      setWatermark(str, display)
    }
  } else {
    // 清空定时
    clearInterval(watermark.interval)
  }
}
export default watermark

 

 

使用

引入
import watermark from '../mixin/watermark'

传参调用
const str = user.userName + ' ' + user.brchName
watermark.set(str, true)// str显示的内容,true启用
watermark.set('', false)// str显示的内容,false关闭
 

 

posted @ 2022-05-25 14:09  Stitchhhhh  阅读(297)  评论(0编辑  收藏  举报