useWatermark.ts 1.8 KB

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