1.directives/index.js
1 import Vue from 'vue' 2 3 Vue.directive('watermark',(el,binding)=>{ 4 function addWaterMarker(str,parentNode,font,textColor){// 水印文字,父元素,字体,文字颜色 5 var can = document.createElement('canvas'); 6 parentNode.appendChild(can); 7 can.width = 200; 8 can.height = 200; 9 can.style.display = 'none'; 10 var cans = can.getContext('2d'); 11 cans.rotate(-45 * Math.PI / 300); 12 cans.font = font || "14px Microsoft JhengHei"; 13 cans.fillStyle = textColor || "rgba(180, 180, 180, 0.3)"; 14 cans.textAlign = 'left'; 15 cans.textBaseline = 'Middle'; 16 cans.fillText(str, can.width / 9, can.height / 2); 17 parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")"; 18 } 19 addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor) 20 })
2.全局引入
1 import './utils/directives'
3.使用
1 <div v-watermark="{text:'水印',textColor:'rgba(180, 180, 180, 0.2)'}">