use-watermark.ts 2.0 KB

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