vue页面添加水印和去除水印
- waterMark.js
'use strict'
const watermark = {}
const setWatermark = (str) => {
const id = '7.432756475.689573874'
if (document.getElementById(id) !== null) {
document.body.removeChild(document.getElementById(id))
}
const can = document.createElement('canvas')
can.width = 350
can.height = 130
const cans = can.getContext('2d')
cans.rotate(-20 * Math.PI / 180)
cans.font = '18px Vedana'
cans.fillStyle = 'rgba(0,0,0,0.06)'
cans.textAlign = 'left'
cans.textBaseline = 'Middle'
cans.fillText(str, can.width / 20, can.height)
const div = document.createElement('div')
div.id = id
div.style.pointerEvents = 'none'
div.style.top = '3px'
div.style.left = '0px'
div.style.position = 'fixed'
div.style.zIndex = '0'
div.style.width = document.documentElement.clientWidth + 'px'
div.style.height = document.documentElement.clientHeight + 'px'
div.style.background = 'url(' + can.toDataURL('image/png') + ') left top repeat'
document.body.appendChild(div)
return id
}
// 该方法只允许调用一次
watermark.set = (str) => {
let id = setWatermark(str)
setInterval(() => {
if (document.getElementById(id) === null) {
id = setWatermark(str)
}
}, 500)
window.onresize = () => {
setWatermark(str)
}
}
let outWatermark = (id) => {
if (document.getElementById(id) !== null) {
const div = document.getElementById(id)
div.style.display = 'none'
}
}
/**
* 该方法只允许调用一次
* @param:
* @text == 水印内容
* @sourceBody == 水印添加在哪里,不传就是body
* */
watermark.out = () => {
let id = '7.432756475.689573874'
outWatermark(id)
}
export default watermark;
2.App.vue页面全局引入
//页面
<div class="navbar" ref="container">
...
</div>
//在mounted中调用
mounted() {
let date = new Date();
this.userName = ‘名称’
this.dateTime = this.dateFormat(new Date(date))
Watermark.set(this.userName + ' ' + this.dateTime, this.$refs.container);
},
//删除水印
Watermark.out()
methods:{
// 格式化时间(水印需要时间可以用这个格式化方法)
dateFormat(date) {
//获取年月日,时间
var year = date.getFullYear();
var mon =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1;
var data = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var min =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seon =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
var newDate =
year + "-" + mon + "-" + data + " " + hour + ":" + min + ":" + seon;
return newDate;
},
}
代码示例
效果图
3.局部引入参考全局引入,根据自己需求放在需要的页面