微信小程序写一个水印组件,直接引用到想要添加水印的页面中
<template>
<view class="watermark-container" :style="{ position: fixed ? 'fixed' : 'absolute' }">
<canvas
class="watermark-canvas"
:style="{
width: '100%',
height: '100%',
pointerEvents: 'none',
top: '0',
left: '0',
zIndex: zIndex
}"
canvas-id="watermarkCanvas"
@loaded="onCanvasLoaded"
></canvas>
</view>
</template>
<script>
export default {
name: 'Watermark',
props: {
text: {
type: String,
default: '水印文字'
},
color: {
type: String,
default: 'rgba(0, 0, 0, 0.12)'
},
fontSize: {
type: Number,
default: 12
},
rotate: {
type: Number,
default: -45
},
gapX: {
type: Number,
default: 100
},
gapY: {
type: Number,
default: 80
},
fixed: {
type: Boolean,
default: true
},
zIndex: {
type: Number,
default: 9999
}
},
data() {
return {
canvasContext: null,
canvasWidth: 0,
canvasHeight: 0
}
},
mounted() {
this.onCanvasLoaded();
},
methods: {
onCanvasLoaded(e) {
const _this = this;
this.canvasContext = wx.createCanvasContext('watermarkCanvas', this)
wx.getSystemInfo({
success: (res) => {
_this.canvasWidth = res.windowWidth
_this.canvasHeight = res.windowHeight
_this.drawWatermark()
}
})
},
drawWatermark() {
if (!this.canvasContext) return
console.log(this.$store)
const ctx = this.canvasContext
const { color, fontSize, rotate, gapX, gapY } = this
const text = '水印文字'
ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
ctx.setFontSize(fontSize)
ctx.setFillStyle(color)
const textMetrics = ctx.measureText(text)
const textWidth = textMetrics.width
const drawWidth = this.canvasWidth + gapX
const drawHeight = this.canvasHeight + gapY
for (let x = -textWidth; x < drawWidth; x += gapX) {
for (let y = 0; y < drawHeight; y += gapY) {
ctx.save()
ctx.translate(x, y)
ctx.rotate(rotate * Math.PI / 180)
ctx.fillText(text, 0, 0)
ctx.restore()
}
}
ctx.draw()
}
},
watch: {
text: 'drawWatermark',
color: 'drawWatermark',
fontSize: 'drawWatermark',
rotate: 'drawWatermark',
gapX: 'drawWatermark',
gapY: 'drawWatermark'
}
}
</script>
<style scoped>
.watermark-container {
width: 100%;
height: 100%;
top: 0;
left: 0;
pointer-events: none;
}
.watermark-canvas {
position: absolute;
}
</style>