创建文件:
utils/watermark.js
import Vue from 'vue'
Vue.directive('watermark', {
bind (el, binding) {
const { text, options } = binding.value
addWatermark(el, text, options)
},
update (el, binding) {
const { text, options } = binding.value
// 这地方应该增加个判断
// 没测试
// if (text) {
// addWatermark(el, text, options)
// } else {
// removeWatermark(el)
// }
removeWatermark(el)
addWatermark(el, text, options)
},
unbind (el) {
removeWatermark(el)
}
})
// 添加水印
function addWatermark (el, text, options = {}) {
const { fontSize = '18px', angle = -30 } = options
const canvas = document.createElement('canvas')
canvas.width = 300
canvas.height = 280
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
ctx.font = `${fontSize} Arial`
ctx.rotate((angle * Math.PI) / 180)
ctx.fillText(text, -70, canvas.height / 2)
ctx.textAlign = 'left'
ctx.textBaseline = 'middle'
const watermarkDiv = document.createElement('div')
watermarkDiv.style.position = 'absolute'
watermarkDiv.style.top = '0'
watermarkDiv.style.left = '0'
watermarkDiv.style.width = '100%'
watermarkDiv.style.height = '100%'
watermarkDiv.style.pointerEvents = 'none'
watermarkDiv.style.backgroundImage = `url('${canvas.toDataURL('image/png')}')`
// watermarkDiv.style.backgroundRepeat = 'repeat'
// watermarkDiv.style.backgroundSize = '100% 100%'
watermarkDiv.style.zIndex = '10000'
el.appendChild(watermarkDiv)
el.__watermarkDiv__ = watermarkDiv
}
// 移除水印
function removeWatermark (el) {
el.style.backgroundImage = 'none'
const watermarkDiv = el.__watermarkDiv__
if (watermarkDiv) {
el.removeChild(watermarkDiv)
delete el.__watermarkDiv__
}
}
使用,再需要添加水印的图层上添加水印
<a-layout-content
:style="{ height: '100%', margin: '24px 8px 0', paddingTop: fixedHeader ? '64px' : '0', position: 'relative' }"
v-watermark="{ text: watermarkStr }"
>
....
....
</a-layout-conten>
<script>
import '@/utils/watermark' // 引入
export default {
data () {
return {
watermarkStr: ''
}
},
methods: {
update() {
// 设置watermarkStr 值,来判断显示隐藏
this.watermarkStr = 'add watermark' // 添加
this.watermarkStr = '' // 移除
}
}
}
</script>
watermarkStr,默认是空值,因为本系统添加的水印有权限控制,所以需要控制显示和隐藏。