水印

效果:


微信截圖_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)
  }
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容