添加水印-->封装好的直接用

104 阅读1分钟
/** * 文字水印 */
const id = '名字.工号'
const setWatermark = (str1 = '', str2 = '') => {
  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }
  const can = document.createElement('canvas')  // 设置canvas画布大小
  can.width = 300
  can.height = 220
  const cans = can.getContext('2d')
  cans.rotate((-25 * Math.PI) / 180) // 水印旋转角度
  cans.font = '24px Vedana'
  cans.fillStyle = '#000'
  cans.textAlign = 'center'
  cans.textBaseline = 'Middle'
  cans.fillText(str1 + ' ' + str2, can.width / 2, can.height) // 水印在画布的位置x,y轴
  // cans.font = '12px Vedana'
  // cans.fillText(str2, can.width / 2, can.height + 22)
  const div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '0px'
  div.style.left = '-100px'
  div.style.opacity = '0.08'
  div.style.position = 'fixed'
  div.style.zIndex = '100000'
  div.style.fontWeight = '100'
  div.style.right = '0'
  div.style.bottom = '0px'
  div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  div.style.backgroundSize = '200px auto'
  document.body.appendChild(div)
  return id
}
// 添加水印方法
export const addWaterMark = (str1, str2) => {
  const _id = setWatermark(str1, str2)
  if (document.getElementById(_id) === null) {
    setWatermark(str1, str2)
  }
}
// 移除水印方法
export const removeWatermark = () => {
  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }
}