vue系列--通过js生成前端水印的方法

此方法开箱即用,在vue项目中import即可。

例如:

//在vue组件中
import Watermark from '@/utils/watermark.js'

//在methods中
Watermark.set({color:"",text:""})//设置水印

Watermark.remove() //删除水印
const watermark = {}

const id = '1.23452384164.123412415'

const setWatermark = (option) => {
  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }

  const can = document.createElement('canvas')
  can.width = 350
  can.height = 250
  const cans = can.getContext('2d')
  cans.rotate(-20 * Math.PI / 180)
  cans.font = '15px Vedana'
  cans.fillStyle = option.color||'rgba(200, 200, 200, 0.30)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(option.text, 1, can.height)

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

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

watermark.remove = () => {
  const obj = document.getElementById(id)
  if (obj != null) {
    obj.parentNode.removeChild(obj)
  }
}

export default watermark

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值