Vue 基于canvas 写一个水印组件
原创
2023-4-6
17:30
编辑于
2023-4-6
17:33
<template>
<div class="watermark">
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
name: 'Watermark',
props: {
text: {
type: String,
default: 'Watermark'
},
// 字体
font: {
type: String,
default: '20px Arial'
},
// 文字颜色
color: {
type: String,
default: 'rgba(0, 0, 0, 0.1)'
},
// 文字水平,垂直方向间隔
gap: {
type: Array,
default: () => [200, 100]
}
},
mounted() {
this.drawWatermark()
window.addEventListener('resize', this.drawWatermark)
},
beforeDestroy() {
window.removeEventListener('resize', this.drawWatermark)
},
methods: {
drawWatermark() {
const can = this.$refs.canvas
const width = window.innerWidth
const height = window.innerHeight
can.width = width
can.height = height
const ctx = can.getContext('2d')
const deg = (40 * Math.PI) / 180
ctx.rotate(-deg)
ctx.font = this.font
ctx.fillStyle = this.color
const textWidth = ctx.measureText(this.text).width
const textHeight = parseInt(this.font, 10)
const startX = -Math.sin(deg) * height
const endY = width / Math.cos(Math.PI / 2 - deg)
for (let i = startX; i < can.width; i += textWidth + this.gap[0]) {
for (let j = 0; j < endY; j += textHeight + this.gap[1]) {
// 填充文字
ctx.fillText(this.text, i, j)
}
}
}
}
}
</script>
<style lang="less" scoped>
.watermark {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
overflow: hidden;
}
</style>
转载请注明出处。本文地址:
https://www.qinshenxue.com/article/vue-writes-a-watermark-component-based-on-canvas.html
关注我的公众号