useWatermark.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const domSymbol = Symbol('watermark-dom')
  2. export function useWatermark(appendEl: HTMLElement | null = document.body) {
  3. let func: Fn = () => {}
  4. const id = domSymbol.toString()
  5. const clear = () => {
  6. const domId = document.getElementById(id)
  7. if (domId) {
  8. const el = appendEl
  9. el && el.removeChild(domId)
  10. }
  11. window.removeEventListener('resize', func)
  12. }
  13. const createWatermark = (str: string) => {
  14. clear()
  15. const can = document.createElement('canvas')
  16. can.width = 300
  17. can.height = 240
  18. const cans = can.getContext('2d')
  19. if (cans) {
  20. cans.rotate((-20 * Math.PI) / 120)
  21. cans.font = '15px Vedana'
  22. cans.fillStyle = 'rgba(0, 0, 0, 0.15)'
  23. cans.textAlign = 'left'
  24. cans.textBaseline = 'middle'
  25. cans.fillText(str, can.width / 20, can.height)
  26. }
  27. const div = document.createElement('div')
  28. div.id = id
  29. div.style.pointerEvents = 'none'
  30. div.style.top = '0px'
  31. div.style.left = '0px'
  32. div.style.position = 'absolute'
  33. div.style.zIndex = '100000000'
  34. div.style.width = document.documentElement.clientWidth + 'px'
  35. div.style.height = document.documentElement.clientHeight + 'px'
  36. div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
  37. const el = appendEl
  38. el && el.appendChild(div)
  39. return id
  40. }
  41. function setWatermark(str: string) {
  42. createWatermark(str)
  43. func = () => {
  44. createWatermark(str)
  45. }
  46. window.addEventListener('resize', func)
  47. }
  48. return { setWatermark, clear }
  49. }