use-watermark.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import type { Watermark, WatermarkOptions } from 'watermark-js-plus';
  2. import { nextTick, onUnmounted, ref, watch } from 'vue';
  3. import { preferences } from '@vben/preferences';
  4. const watermark = ref<Watermark>();
  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. watermark.value?.create();
  46. }
  47. async function updateWatermark(options: Partial<WatermarkOptions>) {
  48. if (!watermark.value || !watermark.value?.check()) {
  49. await initWatermark(options);
  50. } else {
  51. await nextTick();
  52. watermark.value?.changeOptions({
  53. ...cachedOptions.value,
  54. ...options,
  55. });
  56. }
  57. }
  58. function destroyWatermark() {
  59. watermark.value?.destroy();
  60. }
  61. watch(
  62. () => preferences.app.watermark,
  63. (enable) => {
  64. if (!enable) {
  65. destroyWatermark();
  66. }
  67. },
  68. );
  69. onUnmounted(() => {
  70. destroyWatermark();
  71. });
  72. return {
  73. destroyWatermark,
  74. updateWatermark,
  75. watermark,
  76. };
  77. }