Vue 给页面加水印指令(directive)

页面需要水印

import Vue from 'vue'
/**
 * watermark 指令
 * 解决: 给页面生成水印
 * 基本原理:给选择器添加背景图片
 * 用法:v-watermark="{options}"
 * option:
 * @param {string} text 水印文字
 * @param {string} width 宽度
 * @param {string} textColor 文字颜色
 */
Vue.directive('watermark', (el, binding) => {
  function addWaterMarker(str, parentNode, font, textColor) {
    var can = document.createElement('canvas')
    parentNode.appendChild(can)
    can.width = 400
    can.height = 200
    can.style.display = 'none'
    var cans = can.getContext('2d')
    cans.rotate(-20 * Math.PI / 180)
    cans.font = font || '16px Microsoft JhengHei'
    cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
    cans.textAlign = 'center'
    cans.textBaseline = 'Middle'
    cans.fillText(str, can.width / 3, can.height / 2)
    parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
  }
  addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
})

使用(Vue组件)

<div
      class="body"
      id="pdf-container"
      v-watermark="{text:'水印文字',font:'46px Microsoft JhengHei',width:'100%',textColor:'rgba(180, 180, 180, 0.3)'}"
    >
posted @ 2020-07-21 23:29  荣光无限  阅读(1073)  评论(0编辑  收藏  举报