1. Vue3水印组件基础实现
水印功能在前端开发中越来越常见,无论是保护版权内容还是防止敏感信息泄露,水印都扮演着重要角色。在Vue3中实现一个基础水印组件其实并不复杂,我们先从最简单的文字水印开始。
创建一个基本的Watermark.vue组件,核心思路是使用Canvas绘制水印内容,然后将其作为背景图应用到目标元素上。下面是最简化的实现代码:
javascript复制<template>
<div ref="containerRef" style="position: relative">
<slot></slot>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
const containerRef = ref()
const watermarkRef = ref()
const props = defineProps({
content: String,
rotate: { type: Number, default: -22 },
zIndex: { type: Number, default: 9 }
})
function renderWatermark() {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
// 设置canvas大小
canvas.width = 200
canvas.height = 150
// 绘制水印文字
ctx.font = '16px sans-serif'
ctx.fillStyle = 'rgba(0, 0, 0, 0.15)'
ctx.rotate((Math.PI / 180) * props.rotate)
ctx.fillText(props.content, 20, 60)
// 创建水印元素
if (!watermarkRef.value) {
watermarkRef.value = document.createElement('div')
containerRef.value.appendChild(watermarkRef.value)
}
// 应用水印样式
watermarkRef.value.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
background-repeat: repeat;
z-index: ${props.zIndex};
background-image: url('
