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