vben 添加水印组件

1. 水印组件

vben 添加水印组件_第1张图片

import { withInstall } from '/@/utils/index';
import type { DirectiveBinding, App } from 'vue';
function createBase64(
  str: string,
  textSize: number,
  textColor: string,
  textXGap: number,
  textYGap: number,
) {
  const can = document.createElement('canvas');
  const width = textXGap || 300;
  const height = textYGap || width / 3;
  Object.assign(can, { width, height });
  const cans = can.getContext('2d');
  if (cans) {
    cans.rotate((-20 * Math.PI) / 120);
    cans.font = textSize + 'px Microsoft JhengHei' || '16px Microsoft JhengHei';
    cans.fillStyle = textColor || 'rgba(0, 0, 0, 0.15)';
    cans.textAlign = 'left';
    cans.textBaseline = 'middle';
    cans.fillText(str, width / 10, height);
  }
  return can.toDataURL('image/png');
}
const addWaterMarker = (
  str: string,
  parentNode: any,
  textSize: number,
  textColor: string,
  textXGap: number,
  textYGap: number,
) => {
  const el = parentNode;
  const waterMarkerlist = document.getElementsByClassName('waterMarker-box');
  if (waterMarkerlist.length) {
    for (let i = 0; i < waterMarkerlist.length; i++) {
      el.removeChild(waterMarkerlist[i]);
    }
  }
  el.style.position = 'relative';
  const { clientHeight: height, clientWidth: width } = el;
  const div = document.createElement('div');
  div.style.pointerEvents = 'none';
  div.className = 'waterMarker-box';
  div.style.top = '0px';
  div.style.left = '0px';
  div.style.position = 'absolute';
  div.style.height = height + 'px';
  div.style.width = width + 'px';
  div.style.zIndex = '100000';
  div.style.background = `url(${createBase64(
    str,
    textSize,
    textColor,
    textXGap,
    textYGap,
  )}) left top repeat`;
  el.appendChild(div);
};
const waterMarker = {
  mounted(el: DirectiveBinding, binding: DirectiveBinding) {
    let width = '',
      height = '';
    function isReize() {
      const style = document.defaultView.getComputedStyle(el);
      if (width !== style.width || height !== style.height) {
        addWaterMarker(
          binding.value.text,
          el,
          binding.value.textSize,
          binding.value.textColor,
          binding.value.textXGap,
          binding.value.textYGap,
        );
      }
      width = style.width;
      height = style.height;
    }
    el.__vueSetInterval__ = setInterval(isReize, 300);
  },
};
export function setupWaterMarkerDirective(app: App) {
  app.directive('waterMarker', waterMarker);
}
// export default waterMarker;

export const WaterMark = withInstall(waterMarker);

 

2. 使用

(1).全局使用

main.js

import { setupWaterMarkerDirective } from '/@/components/WaterMarker';

// Register global directive

setupWaterMarkerDirective(app);

在页面中:

(2) 单页面使用

import { WaterMarker } from '/@/components/WaterMarker';

directives: {

WaterMarker,

},

vben 添加水印组件_第2张图片

 

 

(561条消息) 九、Vben之可拖拽穿梭框和水印背景如何添加_arguments_zd的博客-CSDN博客

你可能感兴趣的:(javascript,前端,vue.js)