1. 新建一个warterMark.js 文件:
//创建水印(参数依次为,水印文字内容,选择器,偏转角度,字体颜色)
export function createWatemark({
text = '水印',
selectors = 'body',
rotate = -14,
color = 'rgba(144,147,153,0.1)'
} = {}) {
let can = document.createElement('canvas');
let body = document.body;
let nodes = document.querySelectorAll(selectors);
body.appendChild(can);
can.width = text.length * 20;
can.height = text.length * 20;
can.style.display = 'none';
let cans = can.getContext('2d');
// 弧度偏转
cans.rotate(rotate * Math.PI / 180);
cans.font = "14px PingFang SC";
cans.fontWeight = '400';
cans.fontFamily = '-apple-system,BlinkMacSystemFont,Segoe UI,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif,Roboto,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol!important;'
cans.fillStyle = color;
cans.fillText(text, 0, can.height / 2);
for (let i = 0; i < nodes.length; i++) {
nodes[i].style.backgroundImage = "url(" + can.toDataURL("image/png") + ")" + ",url(" + can.toDataURL("image/png") + ")";
nodes[i].style.backgroundPosition = '420px 420px,0px 0px'
}
}
2.在APP.vue 文件中导入
import {createWatemark} from "@/utils/validate"; // 路径根据自己的项目定
在 mounted 函数中调用
<template>
<div id="app" style="display: none" :style="{ display: 'block' }">
<div id="water-copy"></div>
<div id="app-inner">
<keep-alive :include="keepAlivePage">
<router-view class="view-box"></router-view>
</keep-alive>
</div>
<Footer></Footer>
</div>
</template>
<script>
import Footer from '@/components/footer.vue';
import {getNickname, getUsername} from "@/utils/auth";
import {createWatemark} from "@/utils/validate";
export default {
name: "App",
components: {
Footer,
},
data() {
return {
text: ""
}
},
computed: {
keepAlivePage() {
return this.$store.state.keepPage.keepAlivePage;
},
},
created() {
},
mounted() {
this.$nextTick(() => {
if (getNickname() && getUsername()) {
this.text = getNickname() + ' ' + getUsername()
}
const text = this.text
// 水印
createWatemark({
text,
selectors: "#water-copy",
color: "rgba(144,147,153,0.1)",
});
})
},
};
</script>
<style lang="scss">
@import "./assets/font/font.css";
#app {
position: relative;
height: 100%;
.view-box {
height: 100%;
}
}
#water-copy {
position: fixed;
inset: 0px;
overflow: hidden;
z-index: 99999999;
width: 100%;
height: 100vh;
pointer-events: none;
}
</style>
注意:
一般我们的水印内容是当前用户的id 或者 姓名,在App.vue文件的mounted函数中有可能获取不到Vuex或者cookie的用户信息。所以我们可以将调用水印的方法放在router.afterEach() 或者 router.beforeEach()