vue 项目通过vue指令添加水印

在vue项目中通过自定义指令,使用canvas特性生成base64格式的图片文件,并将其设置为背景图片,从而实现页面或组件局部水印效果

1、新建directives.js

import Vue from 'vue'

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 = 'left';
        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)
})

  2、min.js 引入directives.js (我的directives.js文件在utils目录下)

import  '@/utils/directives'

3、调用指令

  如果希望在整个项目中都添加水印,可以在app.vue中使用指令

  

<template>
  <div id="app">
    <router-view v-watermark="{text:'水印名称',textColor:'rgba(180, 180, 180, 0.3)'}" />
  </div>
</template>

  如果希望只给某个组件添加水印,可以直接在组件html中调用指令

  

原文地址:https://www.cnblogs.com/helloluckworld/p/11431083.html