vue2和vue3页面加自定义水印(组件化)
<!-- Watermark.vue -->
<template>
<div class="watermark" ref="watermark"></div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
const props = defineProps({
text: {
type: String,
required: false,
default: "我是水印"
}
});
const watermark = ref(null);
const addWatermark = (text) => {
const watermarkDiv = watermark.value;
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 280;
const ctx = canvas.getContext('2d');
ctx.rotate(-45 * Math.PI / 180);
ctx.font = '18px Arial';
ctx.fillStyle = 'rgba(180, 180, 180, 0.3)';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
watermarkDiv.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`;
watermarkDiv.style.pointerEvents = 'none';
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.top = 0;
watermarkDiv.style.left = 0;
watermarkDiv.style.width = '100%';
watermarkDiv.style.height = '100%';
watermarkDiv.style.zIndex = 9999;
};
onMounted(() => {
addWatermark(props.text);
});
</script>
<style scoped>
.watermark {
background-repeat: repeat;
}
<!-- Watermark.vue -->
<template>
<div class="watermark" ref="watermark"></div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: false,
default: "我是水印"
}
},
mounted() {
this.addWatermark(this.text);
},
methods: {
addWatermark(text) {
const watermarkDiv = this.$refs.watermark;
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext('2d');
ctx.rotate(-20 * Math.PI / 180);
ctx.font = '20px Arial';
ctx.fillStyle = 'rgba(200, 200, 200, 0.50)';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
watermarkDiv.style.backgroundImage = `url(${canvas.toDataURL('image/png')})`;
watermarkDiv.style.pointerEvents = 'none';
watermarkDiv.style.position = 'fixed';
watermarkDiv.style.top = 0;
watermarkDiv.style.left = 0;
watermarkDiv.style.width = '100%';
watermarkDiv.style.height = '100%';
watermarkDiv.style.zIndex = 9999;
}
}
};
</script>
<style scoped>
.watermark {
background-repeat: repeat;
}
</style>