use-watermark.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import type { Watermark, WatermarkOptions } from 'watermark-js-plus';
  2. import { nextTick, onUnmounted, ref } from 'vue';
  3. const watermark = ref<Watermark>();
  4. const cachedOptions = ref<Partial<WatermarkOptions>>({
  5. advancedStyle: {
  6. colorStops: [
  7. {
  8. color: 'gray',
  9. offset: 0,
  10. },
  11. {
  12. color: 'gray',
  13. offset: 1,
  14. },
  15. ],
  16. type: 'linear',
  17. },
  18. // fontSize: '20px',
  19. content: '',
  20. contentType: 'multi-line-text',
  21. globalAlpha: 0.25,
  22. gridLayoutOptions: {
  23. cols: 2,
  24. gap: [20, 20],
  25. matrix: [
  26. [1, 0],
  27. [0, 1],
  28. ],
  29. rows: 2,
  30. },
  31. height: 200,
  32. layout: 'grid',
  33. rotate: 30,
  34. width: 160,
  35. });
  36. export function useWatermark() {
  37. async function initWatermark(options: Partial<WatermarkOptions>) {
  38. const { Watermark } = await import('watermark-js-plus');
  39. cachedOptions.value = {
  40. ...cachedOptions.value,
  41. ...options,
  42. };
  43. watermark.value = new Watermark(cachedOptions.value);
  44. await watermark.value?.create();
  45. }
  46. async function updateWatermark(options: Partial<WatermarkOptions>) {
  47. if (watermark.value) {
  48. await nextTick();
  49. await watermark.value?.changeOptions({
  50. ...cachedOptions.value,
  51. ...options,
  52. });
  53. } else {
  54. await initWatermark(options);
  55. }
  56. }
  57. function destroyWatermark() {
  58. watermark.value?.destroy();
  59. }
  60. onUnmounted(() => {
  61. destroyWatermark();
  62. });
  63. return {
  64. destroyWatermark,
  65. updateWatermark,
  66. watermark,
  67. };
  68. }