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中調用指令

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM