先看效果
话不多说直接上组件
1、Watermark.vue
<template>
<div>
<canvas ref="canvas" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
props: {
// 图片地址
url: {
type: String,
required: true,
default: 'https://img0.baidu.com/it/u=3232582821,3516640051&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1706288400&t=0bcdcc70fdc82051783cb93e87102657'
},
// 图片宽
width: {
type: Number,
required: true,
default: 400
},
// 图片高
height: {
type: Number,
required: true,
default: 300
},
// 水印行数
rows: {
type: Number,
required: true,
default: 3
},
// 水印列数
cols: {
type: Number,
required: true,
default: 3
},
// 水印的文字
text: {
type: String,
required: true,
default: 'Watermark'
}
},
mounted() {
this.drawWatermark();
},
methods: {
drawWatermark() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
const image = new Image();
image.src = this.url
image.onload = () => {
ctx.drawImage(image, 0, 0, this.width, this.height);
ctx.font = '20px Arial';
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
const stepX = this.width / this.cols;
const stepY = this.height / this.rows;
for (let i = -1; i <= this.cols; i++) {
for (let j = -1; j <= this.rows; j++) {
const x = i * stepX + stepX / 2;
const y = j * stepY + stepY / 2;
ctx.save();
ctx.translate(x, y);
ctx.rotate(-Math.PI / 6);
ctx.fillText(this.text, 0, 0);
ctx.restore();
}
}
};
},
},
}
</script>
2、使用
<Watermark
:url="'https://img2.baidu.com/it/u=1814561676,2470063876&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1706288400&t=5c5fb8f24cad1dcb6d526aae674623b0'"
:width="400"
:height="300"
:rows="3"
:cols="3"
:text="'water--mark'"
></Watermark>
3、注意
图片的宽高和水印的行数列数,需要你自己调整,
你的图片需要显示什么宽高就写多少,
然后去调整几行几列能铺满,调整到铺满整个图片适宜为止,
该组件该有可以补充的地方,比如水印大小,水印颜色等,可以自己动手补充哦