话不多说,直接代码
<template>
<view class="wrap">
<u-form :model="model" ref="uForm" >
<u-form-item :label-position="labelPosition" label="照片信息:" prop="photo" label-width="160">
<u-upload width="160"
:deletable="false" // 是否允许删除
:show-progress="false" // 是否展示进度
:source-type="sourceType" // 图片来源
:before-upload="beforeUpload" // 上传前钩子
:action="'服务器地址'"
:header="header" // 上传携带的头信息,对象形式
:form-data = "formData" // 上传额外携带的参数
>
</u-upload>
</u-form-item>
</u-form>
<view style="position: absolute;top: -999999px;">
<view>
<canvas style="width: 1000px;height: 1000px;" canvas-id="firstCanvas"></canvas>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
header: {
'X-Access-Token': uni.getStorageSync('token')
},
formData: {
'biz': 'mobile'
},
sourceType: ['camera']
};
},
methods: {
// 上传照片
async beforeUpload(index, list) {
uni.showLoading({
title: '上传中...',
})
var data = await this.getWatermark(index, list);
uni.hideLoading()
return data;
},
//照片添加水印
getWatermark(index, list){
return new Promise((resolve, reject) => {
var that = this;
uni.getImageInfo({
src: list[index].url,
success: (ress) => {
let ctx = uni.createCanvasContext('firstCanvas'); //创建画布
//将图片src放到cancas内,宽高为图片大小
ctx.drawImage(list[index].url, 0, 0, ress.width / 3, ress.height / 3)
ctx.setFontSize(15) //字体大小
ctx.setFillStyle('#ffffff') //字体颜色
let textToWidth = ress.width / 3 * 0.3; //字体宽度
let textToHeight = ress.height / 3 * 0.9; //字体高度
ctx.fillText("这是水印", textToWidth, textToHeight) // 设置字体
ctx.draw(false,()=>{
setTimeout(() => {//使用定时是因为制作水印需要时间,设置定时才不会出bug
uni.canvasToTempFilePath({//将画布中内容转成图片,即水印与图片合成
width: ress.width / 3, // 画布宽
height: ress.height / 3, // 画布高
canvasId: 'firstCanvas',
success: (res) => {
list[index].url = res.tempFilePath
uni.saveImageToPhotosAlbum({//保存到手机
filePath: res.tempFilePath,
success: (re) => {
resolve(true);
}
})
}
})
}, 500)
});
}
})
})
}
}
};
</script>
<style scoped lang="scss">
.wrap {
padding: 30rpx;
}
</style>
注:1.样式参考uview的Upload 上传组件
组件地址
http://uviewui.com/components/upload.html
2.参考文章:
https://www.jianshu.com/p/7cb98266fc81
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)