我用到的组件库是ant-design-vue
//:before-upload
<a-upload
class="avatar-uploader"
list-type="picture-card"
:file-list="uploadFileList"
:custom-request="uploadDoneHandle"
:before-upload="beforeUploadHandle"
:remove="removeHandle"
v-decorator="['path', { rules: formValidateRules.path }]"
@preview="previewHandle"
@change="uploadChangeHandle"
>
<div v-if="uploadFileList.length < 1">
<a-icon :type="uploadLoading ? 'loading' : 'plus'" />
</div>
</a-upload>
beforeUploadHandle这个方法中去生成水印,然后通过后端上传接口,把图片传给后端,然后再接收后端返回的数据
beforeUploadHandle(file) {
return new Promise((resolve) => {
const reader = new FileReader()
reader.readAsDataURL(file) // file转base64
reader.onload = (e) => {
const canvas = document.createElement('canvas')
const img = new Image()
img.src = e.target.result
img.onload = () => {
const ctx = canvas.getContext('2d')
let data = ''
const imgWidth = img.width
const imgHeight = img.height
// const fontsize = imgWidth > imgHeight ? imgHeight / 10 : imgWidth / 10// 设定文字大小随图片大小变化
canvas.width = imgWidth // 画布宽度
canvas.height = imgHeight // 画布高度
ctx.drawImage(img, 0, 0, imgWidth, imgHeight) // 绘制图片大小和先前图片一致
for (let i = 0; i < 6; i++) {
ctx.save()
ctx.translate(i + 50, i + 50)
ctx.rotate((45 * Math.PI) / 180)
ctx.fillStyle = 'rgb(0,0,0,0.3)' // 水印颜色,透明度
ctx.textBaseline = 'center' // 水印对其的基准线
ctx.font = `50px Verdana` // 文字大小
ctx.fillText('严禁搬运', imgWidth / 2 - i * 200, imgHeight / 2 - i * 200) // 添加的文字
ctx.restore()
ctx.save()
ctx.translate(i + 600, i + 600)
ctx.rotate((45 * Math.PI) / 180)
ctx.fillStyle = 'rgb(0,0,0,0.4)' // 水印颜色,透明度
ctx.textBaseline = 'center' // 水印对其的基准线
ctx.font = `50px Verdana` // 文字大小
ctx.fillText('仅供展示,严禁盗用,复印无效', imgWidth / 2 - i * 200, imgHeight / 2 - i * 200) // 添加的文字
ctx.restore()
}
data = canvas.toDataURL(file.type) // 输出压缩后的base64
// base64转file
const arr = data.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
const files = new File([new Blob([u8arr], { type: mime })], file.name, { type: file.type })
files.uid = file.uid
resolve(files)
}
}
})
},
上面代码中的for里面是对图片水印的角度,字体大小,中心点,以及数量上做一个调整