1、步骤说明
第一步:uni.chooseImage,获取图片的临时路径
第二步:uni.getImageInfo,获取图片的宽高作为画布的大小
第三步:uni.createCanvasContext,创建 canvas 绘图上下文,在画布中画文字水印
第四步:uni.canvasToTempFilePath,把当前画布指定区域的内容转换成指定大小的图片
第五步:页面渲染
2、代码
<template>
<view class="upload">
<view class="upload-img">
<view v-for="item in list" :key="item" class="upload-img-box">
<image :src="item" class="img-style"></image>
</view>
</view>
<view class="upload-btn">
<button type="primary" @click="getFile">上传图片</button>
</view>
<canvas
style="position: absolute; left: -5000px"
:style="{ width: cisternWidth + 'px', height: cisternHeight + 'px' }"
canvas-id="imgCanvas"
></canvas>
</view>
</template>
<script>
export default {
data() {
return {
list: [],
cisternWidth: 160,
cisternHeight: 160,
};
},
onLoad() {},
methods: {
getFile() {
uni.chooseImage({
count: 4,
sizeType: ["compressed"],
success: async (res) => {
const filePath = res.tempFilePaths;
let tempList = [];
uni.showLoading({
title: "处理中",
});
for (let i = 0, length = filePath.length; i < length; i++) {
await this.dealFile(filePath[i]).then((res) => {
tempList.push(res.tempFilePath);
});
}
this.list = [...this.list, ...tempList];
uni.hideLoading();
},
});
},
dealFile(path) {
return new Promise((resolve) => {
uni.getImageInfo({
src: path,
success: (res) => {
const ctx = uni.createCanvasContext("imgCanvas", this);
const { width, height, path } = res;
const fontSize = width / 20;
const space = height * 0.05;
this.cisternWidth = width;
this.cisternHeight = height;
// 初始化画布
ctx.fillRect(0, 0, width, height);
// 画布上面绘制图片
ctx.drawImage(path, 0, 0, width, height);
// 设置阴影的模糊程度 默认0
ctx.shadowBlur = 3;
// 设置阴影颜色效果
ctx.shadowColor = "#ffffff";
// 设置文字大小
ctx.font = fontSize + "px Arial";
// 颜色
ctx.setFillStyle("#2d2d2d");
ctx.fillText("春蚕到死丝方尽", 5, space);
ctx.fillText("蜡炬成灰泪始干", 5, space + fontSize + 5);
ctx.draw(false, () => {
setTimeout(() => {
// 将画布内容转换成图片
uni.canvasToTempFilePath({
canvasId: "imgCanvas",
fileType: "jpg",
quality: 1,
success: (res) => {
resolve(res);
},
});
}, 500);
});
},
});
});
},
},
};
</script>
<style lang="scss" scoped>
.upload {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
&-img {
flex: 1;
overflow: scroll;
text-align: center;
&-box {
font-size: 0;
.img-style {
width: 250px;
margin: 5px 0;
}
}
}
&-btn {
width: 100vw;
> button {
border-radius: 0;
}
}
}
</style>
3、结果