// 对应文件引入包含下面内容的js文件,并且顺序在引入vue.js之后
<div class="title" v-watermark></div>
js文件
//vue的自定义指令
Vue.directive('watermark',(el,binding)=>{
let text1 = "文字一";
let time = new Date;
// 当前日期的月日时分
let text2 = (time.getMonth() + 1) + "" + time.getDate() + "" + time.getHours() + "" + time.getMinutes();
let font = "12px Microsoft JhengHei";
let textColor = "rgba(192, 192, 192, 0.3)";
// 根据两个文字的长度设置每一个模块的长度
let width = text1.length > text2.length ? (text1.length * 12 + 40) : (text2.length * 12 + 40) || 150;
let height = 80;
// 倾斜角度
let textRotate = -20;
function addWaterMarker(parentNode){
var can = document.createElement('canvas');
parentNode.appendChild(can);
can.width = width;
can.height = height;
can.style.display = 'none';
var cans = can.getContext('2d');
cans.rotate(textRotate * Math.PI / 180);
cans.font = font;
cans.fillStyle = textColor;
cans.textAlign = 'left';
cans.textBaseline = 'Middle';
cans.fillText(text1, 0, height);
cans.fillText(text2, 0, height - 30);
// 将水印返回成图片
parentNode.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
}
addWaterMarker(el)
})