use-watermark.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import type { Watermark, WatermarkOptions } from 'watermark-js-plus';
  2. import { nextTick, onUnmounted, readonly, ref } from 'vue';
  3. const watermark = ref<Watermark>();
  4. const unmountedHooked = ref<boolean>(false);
  5. const cachedOptions = ref<Partial<WatermarkOptions>>({
  6. advancedStyle: {
  7. colorStops: [
  8. {
  9. color: 'gray',
  10. offset: 0,
  11. },
  12. {
  13. color: 'gray',
  14. offset: 1,
  15. },
  16. ],
  17. type: 'linear',
  18. },
  19. // fontSize: '20px',
  20. content: '',
  21. contentType: 'multi-line-text',
  22. globalAlpha: 0.25,
  23. gridLayoutOptions: {
  24. cols: 2,
  25. gap: [20, 20],
  26. matrix: [
  27. [1, 0],
  28. [0, 1],
  29. ],
  30. rows: 2,
  31. },
  32. height: 200,
  33. layout: 'grid',
  34. rotate: 30,
  35. width: 160,
  36. });
  37. export function useWatermark() {
  38. async function initWatermark(options: Partial<WatermarkOptions>) {
  39. const { Watermark } = await import('watermark-js-plus');
  40. cachedOptions.value = {
  41. ...cachedOptions.value,
  42. ...options,
  43. };
  44. watermark.value = new Watermark(cachedOptions.value);
  45. await watermark.value?.create();
  46. }
  47. async function updateWatermark(options: Partial<WatermarkOptions>) {
  48. if (watermark.value) {
  49. await nextTick();
  50. await watermark.value?.changeOptions({
  51. ...cachedOptions.value,
  52. ...options,
  53. });
  54. } else {
  55. await initWatermark(options);
  56. }
  57. }
  58. function destroyWatermark() {
  59. if (watermark.value) {
  60. watermark.value.destroy();
  61. watermark.value = undefined;
  62. }
  63. }
  64. // 只在第一次调用时注册卸载钩子,防止重复注册以致于在路由切换时销毁了水印
  65. if (!unmountedHooked.value) {
  66. unmountedHooked.value = true;
  67. onUnmounted(() => {
  68. destroyWatermark();
  69. });
  70. }
  71. return {
  72. destroyWatermark,
  73. updateWatermark,
  74. watermark: readonly(watermark),
  75. };
  76. }