效果
代码,存放位置 /utils/waterMark.js
//waterMark.js文件
let waterMark = {}
let setWaterMark = (str,str1) => {
let id = '1.23452384164.123412416';
if (document.getElementById(id) !== null) {
//ui-table是table上的一个样式,一般水印显示在这个table上
if(document.getElementsByClassName("ui-table")[0]){
document.getElementsByClassName("ui-table")[0].removeChild(document.getElementById(id));
}
}
//创建一个画布
let can = document.createElement('canvas');
//设置画布的长宽
can.width = 400;
can.height = 239;
let cans = can.getContext('2d');
//旋转角度
cans.rotate(-55 * Math.PI / 550);
//设置字体 和字体大小
cans.font = '18px FZXiaoBiaoSong';
//can.style.letterSpacing = '5px';
//设置填充绘画的颜色、渐变或者模式
cans.fillStyle = 'rgba(225, 221, 221, 0.35)';
//设置文本内容的当前对齐方式
cans.textAlign = 'left';
//设置在绘制文本时使用的当前文本基线
cans.textBaseline = 'Middle';
//设置间距
can.style.letterSpacing = '55px';
cans.fillText(str1+" "+str, can.width / 8, can.height / 2);
let div = document.createElement('div');
div.id = id;
div.style.pointerEvents = 'none';
div.style.top = '0';
div.style.left = '0';
div.style.position = 'absolute';
div.style.zIndex = '100000';
div.style.width = "100%";
div.style.height = "100%";
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat';
if(document.getElementsByClassName("ui-table")[0]){
document.getElementsByClassName("ui-table")[0].appendChild(div);
}
return id;
}
// 该方法只允许调用一次
waterMark.set = (str,str1) => {
let id = setWaterMark(str,str1);
setInterval(() => {
if (document.getElementById(id) === null) {
id = setWaterMark(str,str1);
}
}, 500);
window.onresize = () => {
setWaterMark(str,str1);
};
}
export default waterMark;
main.js引用
import waterMark from '@/utils/waterMark.js';
Vue.prototype.$waterMark = waterMark
页面的生命周期调用
mounted(){
//添加水印
this.$waterMark.set(moment(new Date()).format('yyyy-MM-DD HH:mm:ss'),sessionStorage.getItem('realname'))
},