useWatermark.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import { getCurrentInstance, onBeforeUnmount, ref, Ref, shallowRef, unref } from 'vue';
  2. import { useRafThrottle } from '@jeesite/core/utils/domUtils';
  3. import { addResizeListener, removeResizeListener } from '@jeesite/core/utils/event';
  4. import { isDef } from '@jeesite/core/utils/is';
  5. const watermarkSymbol = 'watermark-dom';
  6. const updateWatermarkText = ref<string | null>(null);
  7. type UseWatermarkRes = {
  8. setWatermark: (str: string) => void;
  9. clear: () => void;
  10. clearAll: () => void;
  11. waterMarkOptions?: waterMarkOptionsType;
  12. obInstance?: MutationObserver;
  13. targetElement?: HTMLElement;
  14. parentElement?: HTMLElement;
  15. };
  16. type waterMarkOptionsType = {
  17. // 自定义水印的文字大小
  18. fontSize?: number;
  19. // 自定义水印的文字颜色
  20. fontColor?: string;
  21. // 自定义水印的文字字体
  22. fontFamily?: string;
  23. // 自定义水印的文字对齐方式
  24. textAlign?: CanvasTextAlign;
  25. // 自定义水印的文字基线
  26. textBaseline?: CanvasTextBaseline;
  27. // 自定义水印的文字倾斜角度
  28. rotate?: number;
  29. };
  30. const sourceMap = new Map<symbol, Omit<UseWatermarkRes, 'clearAll'>>();
  31. function findTargetNode(el) {
  32. return Array.from(sourceMap.values()).find((item) => item.targetElement === el);
  33. }
  34. function createBase64(str: string, waterMarkOptions: waterMarkOptionsType) {
  35. const can = document.createElement('canvas');
  36. const width = 300;
  37. const height = 240;
  38. Object.assign(can, { width, height });
  39. const cans = can.getContext('2d');
  40. if (cans) {
  41. const fontFamily = waterMarkOptions?.fontFamily || 'Vedana';
  42. const fontSize = waterMarkOptions?.fontSize || 15;
  43. const fontColor = waterMarkOptions?.fontColor || 'rgba(0, 0, 0, 0.15)';
  44. const textAlign = waterMarkOptions?.textAlign || 'left';
  45. const textBaseline = waterMarkOptions?.textBaseline || 'middle';
  46. const rotate = waterMarkOptions?.rotate || 20;
  47. cans.rotate((-rotate * Math.PI) / 180);
  48. cans.font = `${fontSize}px ${fontFamily}`;
  49. cans.fillStyle = fontColor;
  50. cans.textAlign = textAlign;
  51. cans.textBaseline = textBaseline;
  52. cans.fillText(str, width / 20, height);
  53. }
  54. return can.toDataURL('image/png');
  55. }
  56. const resetWatermarkStyle = (element: HTMLElement, watermarkText: string, waterMarkOptions: waterMarkOptionsType) => {
  57. element.className = '__' + watermarkSymbol;
  58. element.style.pointerEvents = 'none';
  59. element.style.display = 'block';
  60. element.style.visibility = 'visible';
  61. element.style.top = '0px';
  62. element.style.left = '0px';
  63. element.style.position = 'absolute';
  64. element.style.zIndex = '100000';
  65. element.style.height = '100%';
  66. element.style.width = '100%';
  67. element.style.background = `url(${createBase64(
  68. unref(updateWatermarkText) || watermarkText,
  69. waterMarkOptions,
  70. )}) left top repeat`;
  71. };
  72. const obFn = () => {
  73. const obInstance = new MutationObserver((mutationRecords) => {
  74. for (const mutation of mutationRecords) {
  75. for (const node of Array.from(mutation.removedNodes)) {
  76. const target = findTargetNode(node);
  77. if (!target) return;
  78. const { targetElement, parentElement } = target;
  79. // 父元素的子元素水印如果被删除 重新插入被删除的水印(防篡改,插入通过控制台删除的水印)
  80. if (!parentElement?.contains(targetElement as Node | null)) {
  81. target?.parentElement?.appendChild(node as HTMLElement);
  82. }
  83. }
  84. if (mutation.type === 'attributes' && mutation.target) {
  85. // 修复控制台可以”Hide element” 的问题
  86. const _target = mutation.target as HTMLElement;
  87. const target = findTargetNode(_target);
  88. if (target) {
  89. // 禁止改属性 包括class 修改以后 mutation.type 也等于 'attributes'
  90. // 先解除监听 再加一下
  91. clearAll();
  92. target.setWatermark(target.targetElement?.['data-watermark-text']);
  93. }
  94. }
  95. }
  96. });
  97. return obInstance;
  98. };
  99. export function useWatermark(
  100. appendEl: Ref<HTMLElement | null> = ref(document.body) as Ref<HTMLElement>,
  101. waterMarkOptions: waterMarkOptionsType = {},
  102. ): UseWatermarkRes {
  103. const domSymbol = Symbol(watermarkSymbol);
  104. const appendElRaw = unref(appendEl);
  105. if (appendElRaw && sourceMap.has(domSymbol)) {
  106. const { setWatermark, clear } = sourceMap.get(domSymbol) as UseWatermarkRes;
  107. return { setWatermark, clear, clearAll };
  108. }
  109. const func = useRafThrottle(function () {
  110. const el = unref(appendEl);
  111. if (!el) return;
  112. const { clientHeight: height, clientWidth: width } = el;
  113. updateWatermark({ height, width });
  114. });
  115. const watermarkEl = shallowRef<HTMLElement>();
  116. const clear = () => {
  117. const domId = unref(watermarkEl);
  118. watermarkEl.value = undefined;
  119. const el = unref(appendEl);
  120. sourceMap.has(domSymbol) && sourceMap.get(domSymbol)?.obInstance?.disconnect();
  121. sourceMap.delete(domSymbol);
  122. if (!el) return;
  123. domId && el.removeChild(domId);
  124. removeResizeListener(el, func);
  125. };
  126. function updateWatermark(
  127. options: {
  128. width?: number;
  129. height?: number;
  130. str?: string;
  131. } = {},
  132. ) {
  133. const el = unref(watermarkEl);
  134. if (!el) return;
  135. if (isDef(options.width)) {
  136. el.style.width = `${options.width}px`;
  137. }
  138. if (isDef(options.height)) {
  139. el.style.height = `${options.height}px`;
  140. }
  141. if (isDef(options.str)) {
  142. el.style.background = `url(${createBase64(options.str, waterMarkOptions)}) left top repeat`;
  143. }
  144. }
  145. const createWatermark = (str: string) => {
  146. if (unref(watermarkEl) && sourceMap.has(domSymbol)) {
  147. updateWatermarkText.value = str;
  148. updateWatermark({ str });
  149. return;
  150. }
  151. const div = document.createElement('div');
  152. div['data-watermark-text'] = str; //自定义属性 用于恢复水印
  153. updateWatermarkText.value = str;
  154. watermarkEl.value = div;
  155. resetWatermarkStyle(div, str, waterMarkOptions);
  156. const el = unref(appendEl);
  157. if (!el) return;
  158. const { clientHeight: height, clientWidth: width } = el;
  159. updateWatermark({ str, width, height });
  160. el.appendChild(div);
  161. sourceMap.set(domSymbol, {
  162. setWatermark,
  163. clear,
  164. parentElement: el,
  165. targetElement: div,
  166. obInstance: obFn(),
  167. waterMarkOptions,
  168. });
  169. sourceMap.get(domSymbol)?.obInstance?.observe(el, {
  170. childList: true, // 子节点的变动(指新增,删除或者更改)
  171. subtree: true, // 该观察器应用于该节点的所有后代节点
  172. attributes: true, // 属性的变动
  173. });
  174. };
  175. function setWatermark(str: string) {
  176. createWatermark(str);
  177. addResizeListener(document.documentElement, func);
  178. const instance = getCurrentInstance();
  179. if (instance) {
  180. onBeforeUnmount(() => {
  181. clear();
  182. });
  183. }
  184. }
  185. return { setWatermark, clear, clearAll };
  186. }
  187. function clearAll() {
  188. Array.from(sourceMap.values()).forEach((item) => {
  189. item?.obInstance?.disconnect();
  190. item.clear();
  191. });
  192. }