水印

效果:


微信截图_20240618135045.png
import { useThemeStore } from '@/store/theme'
const themeStore = useThemeStore()
const setWatermark = (str: any) => {
  const id = '1.23452384164.123412416'
  if (!str) {
    if (document.getElementById(id) !== null) {
      document.body.removeChild(document.getElementById(id)!)
    }
    return ''
  }
  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id)!)
  }
  let txtX = 2
  let leftXB = 4
  let rightXB = 0
  let width = 200
  let watermarkColor = themeStore.scheme == 'dark' ? '#3A3A40' : '#c3c8d3'
  if (str && str.length > 2) {
    txtX = 3
    leftXB = 6
    rightXB = 25
    width = 220
  }
  // 创建一个画布
  const ctx = document.createElement('canvas')
  // 设置画布的长宽
  ctx.width = width
  ctx.height = width
  const cans = ctx.getContext('2d')!
  // cans.rect(0, 0, ctx.width, ctx.height)
  // 文字
  // 旋转角度
  cans.rotate((45 * Math.PI) / 180)
  cans.font = '38px Source Han Sans CN'
  //设置填充绘画的颜色、渐变或者模式
  cans.fillStyle = watermarkColor
  //设置文本内容的当前对齐方式
  cans.textAlign = 'start'
  //设置在绘制文本时使用的当前文本基线
  // cans.textBaseline = 'middle'
  //在画布上绘制填色的文本(输出的文本,开始绘制文本的X坐标位置,开始绘制文本的Y坐标位置)
  cans.fillText(str, ctx.width / txtX, ctx.height / 4)
  // 左边横线
  let lry = ctx.height / 6
  let x = ctx.width / 1.45
  let leftX = ctx.width / leftXB
  let leftWidth = 20 // 左右横线长度
  let topWidth = 30 // 上下横线长度
  let lineWidth = 2 // 线宽
  cans.moveTo(leftX, lry) // 起点
  cans.lineTo(leftX + leftWidth, lry) //  终点
  // 右边横线
  let rightX = ctx.width + rightXB
  cans.moveTo(rightX, lry) // 起点
  cans.lineTo(rightX + leftWidth, lry) //  终点
  // 上横线
  let topY = -(ctx.height / 5)
  cans.moveTo(x, topY) // 起点
  cans.lineTo(x, topY + topWidth) //  终点
  // 下横线
  let bottomY = ctx.height / 2.5
  cans.moveTo(x, bottomY) // 起点
  cans.lineTo(x, bottomY + topWidth) //  终点
  cans.lineWidth = lineWidth //  线宽
  cans.strokeStyle = watermarkColor //  线样式
  cans.stroke() //  绘制

  const div = document.createElement('div')
  div.id = id
  div.style.pointerEvents = 'none'
  div.style.top = '-50px'
  div.style.left = '0px'
  div.style.position = 'fixed'
  div.style.zIndex = '102'
  div.style.width = document.documentElement.clientWidth + 'px'
  div.style.height = document.documentElement.clientHeight + 'px'
  div.style.background =
    'url(' + ctx.toDataURL('image/png') + ') left top repeat'
  document.body.appendChild(div)
  return id
}
export const getmark = (str: string) => {
  let id = setWatermark(str)
  // setInterval(() => {
  //   if (document.getElementById(id) === null) {
  //     id = setWatermark(str)
  //   }
  // }, 500)
  window.onresize = () => {
    setWatermark(str)
  }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容