项目场景:
提示:这里简述项目相关背景:
uni-app上传图片添加文字水印功能时图片只显示左上角,或者图片重叠
图片不规则一系列bug,特此记录
问题描述
提示:这里描述项目中遇到的问题:
上传图片后图片有时显示不完整
代码测试如下:可直接复制进行测试(这段代码复制出去可以暂测试,但会出现项目场景的问题,有时间之人可直接测试)
<template>
<view class="addWater">
<view class="canvas_view">
<canvas canvas-id="watermarkCanvas" :style="{width:width+'px',height:height+'px'}"></canvas>
</view>
<view class="" @click="chooseImg">图片添加水印</view>
<view class="imageList">
<image :src="item" mode="" v-for="(item,index) in imgList" :key="index" @click="previewImg(index)"></image>
</view>
</view>
</template>
<script>
export default {
data() {
return {
width: 1980,
height: 2340,
context: '',
imgList: []
}
},
onLoad() {
},
methods: {
// 选择图片
chooseImg() {
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], //从相册选择
success: (res) => {
let file = res.tempFilePaths[0];
this.getImgInfo(file)
}
});
},
getImgInfo(file) {
uni.getImageInfo({
src: file,
success: (image) => {
let context = uni.createCanvasContext('watermarkCanvas', this)
this.width = image.width;
this.height = image.height;
context.fillRect(0, 0, this.width, this.height);
// 将图片src放到cancas内,宽高为图片大小
console.log(file == image.path);
context.drawImage(file, 0, 0, this.width, this.height)
let obj = {
time: '时间:2022-02-03 14:23:25',
adress: '地址:XXXXXXXXX',
perple: '运维人员:XXX'
}
context.beginPath();
context.setFontSize(32);
context.setFillStyle("rgba(255,255,255,1)");
//水印在右上角
//0左上角横坐标(向右移)40 左上角纵坐标(向下移)
context.fillText(obj.time, 10, (image.height - 140));
context.fillText(obj.adress, 10,(image.height - 90));
context.fillText(obj.perple, 10,(image.height - 40));
//水印在左上角
// context.fillText(obj.time, 10, 40);
// context.fillText(obj.adress, 10, 90);
// context.fillText(obj.perple, 10, 140);
//占位坑 1
context.draw(false, () => {
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: image.width,
height: image.height,
destWidth: image.width,
destHeight: image.height,
canvasId: 'watermarkCanvas',
fileType: 'png',
success: (res) => {
this.imgList.push(res.tempFilePath)
},
fail: (err) => {
console.log(err)
},
complete: () => {
// uni.hideLoading();
}
}, this);
})
//暂位坑 2
}
})
},
previewImg(index) {
uni.previewImage({
urls: this.imgList,
current: index,
})
}
}
}
</script>
<style scoped lang="scss">
.canvas_view {
width: 0;
height: 0;
overflow: hidden;
}
.imageList {
width: 100%;
margin-top: 50rpx;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
image {
width: 180rpx;
height: 180rpx;
margin-bottom: 30rpx;
}
}
</style>
原因分析:
原因分析:这里填写问题的分析:出现项目场景的问题原因是因为画布的draw函数是异步的,有可能会因为你在上传第二张图片时,第一张的图片大小画布影响了
解决方案:
提示:这里填写该问题的具体解决方案:直接在上方测试的代码上的占位坑中加一个定时器 占位坑1:setTimeout(()=>{ 占位坑2: },300) 300ms只是举例,可随意修改
注意:这里我只测试1张1张图片上传,多张图片暂未测试(可直接按项目情况for循环)
总结
提示:这里对文章进行总结:
送自己和大家一句话吧:乾坤未定,你我皆是黑马!!!加油