效果图:
1、在项目components文件中新建watermark.vue文件:
<template>
<div class="watermark-container">
<div v-for="(position, index) in watermarkPositions" :key="index" class="watermark"
:style="{ top: position.top, left: position.left }">{{ watermarkText }}</div>
<slot>
<!-- 预留出插槽,以便于页面组件的嵌入 -->
</slot>
</div>
</template>
<script>
export default {
data() {
return {
watermarkText: '章小鱼爱吃鱼 7758521', // 替换为你需要的水印 ---可根据接口赋值或vuex改变
watermarkPositions: []
}
},
mounted() {
this.addWatermark();
window.addEventListener('resize', this.addWatermarks); //监听窗口变化
},
beforeDestroy() {
window.removeEventListener('resize', this.addWatermarks);//销毁
},
methods: {
addWatermark() {
// 添加水印的逻辑,可以使用 DOM 操作或者 CSS 类添加样式
// 例如,设置文字颜色、透明度、字体大小、旋转角度等
const container = document.querySelector('.watermark-container');
const {
width,
height
} = container.getBoundingClientRect();
const diagonalLength = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));
const numWatermarks = Math.ceil(diagonalLength / 200); // 每个水印之间的间隔为200,可以根据需要调整--数量
this.watermarkPositions = [];
const angle = Math.atan(height / width);
let position = ''
for (let i = 0; i < numWatermarks; i++) {
for (let j = 0; j < numWatermarks; j++) {
position = {
top: `${(i * height) / numWatermarks}px`,
left: `${(j * Math.tan(angle) * height) / numWatermarks + 160*j}px`//设置水平间距多加160,可以根据需要调整
};
this.watermarkPositions.push(position);
}
}
}
}
}
</script>
<style>
.watermark-container {
position: relative;
width: 100%;
min-height: 750px;
overflow: hidden;
}
.watermark {
position: absolute;
top: 50%;
left: 50%;
transform: rotate(-45deg);
color: rgba(0, 0, 0, 0.3);
font-size: 20px;
/* 禁止换行 */
white-space: nowrap;
/* 禁止鼠标事件 */
pointer-events: none;
/* 确保水印在最顶层 */
z-index: 9999;
/* 设置水印透明度 */
opacity: 0.3;
/* 指定水印图片路径 */
/* background-image: url('path/to/your/watermark.png'); */
/* 设置水印平铺方式 */
/* background-repeat: repeat; */
}
</style>
2、使用:
!!!!本案例是全局页面使用,在Main.vue中:
<watermark>
<!-- 使用预留的插槽 将所有的子组件页面导入 -->
<router-view></router-view>
</watermark>
<script>
import watermark from '../components/watermark'
export default {
components: {
watermark
},
}
</script>