添加水印

优点:不分框架,vue2,vue3,react,使用javascript实现,删除水印或者设置隐藏都会重新渲染水印,使其一直存在。

创建watermark.js文件

使用MutationObserver对元素进行监听,若是水印元素被删除/被设置为display:none;都会重新渲染。
可以更改cans部分实现自己的特殊水印定制,目前只支持文字水印。

const watermark = {}

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

  // 创建水印元素
  const createWatermark = () => {
    const can = document.createElement('canvas')
    can.width = 360
    can.height = 280

    const cans = can.getContext('2d')
    cans.rotate((-20 * Math.PI) / 180)
    cans.font = '20px Vedana'
    cans.fillStyle = 'rgba(200, 200, 200, 0.4)'
    cans.textAlign = 'left'
    cans.textBaseline = 'middle'
    cans.fillText(str, can.width / 3, can.height / 2)
    cans.fillText(str1, can.width / 3, can.height / 1.7)

    const div = document.createElement('div')
    div.id = id
    div.style.pointerEvents = 'none'
    div.style.position = 'fixed'
    div.style.top = '0'
    div.style.left = '0'
    div.style.width = `${document.documentElement.clientWidth}px`
    div.style.height = `${document.documentElement.clientHeight}px`
    div.style.zIndex = '9999'
    div.style.background = `url(${can.toDataURL('image/png')}) left top repeat`
    document.body.appendChild(div)
    return div
  }

  // 检查是否已存在水印元素
  if (document.getElementById(id) === null) {
    watermark.element = createWatermark()
  } else {
    watermark.element.style.display = 'block' // 确保显示
  }

  return id
}

// 监听DOM变动
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList' && watermark.element && !document.body.contains(watermark.element)) {
      setWatermark(watermark.str, watermark.str1)
    }
    if (mutation.type === 'attributes' && mutation.target === watermark.element) {
      if (mutation.attributeName === 'style' && watermark.element.style.display === 'none') {
        setWatermark(watermark.str, watermark.str1)
      }
    }
  })
})

// 开始观察
observer.observe(document.body, { childList: true, subtree: true, attributes: true })

// 设置水印
watermark.set = (str, str1) => {
  watermark.str = str
  watermark.str1 = str1
  let id = setWatermark(str, str1)
  setInterval(() => {
    if (document.getElementById(id) === null) {
      id = setWatermark(str, str1)
    }
  }, 500)
  window.addEventListener('resize', () => {
    setWatermark(str, str1)
  })
}

export default watermark

使用水印

import watermark from '@/core/watermark'
watermark.set('水印一号', '水印二号')

0/500
评论列表