微信小程序–上传图片加水印
wxml
<canvas class='canvas' canvas-id="firstCanvas"></canvas>
css
.canvas{
border: 2rpx solid pink;
background: pink;
width: 100%;
height: 100%;
}
js
ChooseImage() {
var _this = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album'],
success: (res) => {
var tempFilePaths = res.tempFilePaths;
this.setData({
uploadimgcount: tempFilePaths.length,
alreadyUploadSuccessCount: 0
});
for (let item of tempFilePaths) {
console.log(item)
let file = {
reportFileName: "",
localUrl: item,
reportFile: ""
}
this.uploadimg(item);
}
if (this.data.imgList.length != 0) {
this.setData({
imgList: this.data.imgList.concat(res.tempFilePaths)
})
} else {
this.setData({
imgList: res.tempFilePaths
})
}
_this.watermark();
}
});
},
watermark() {
let _this = this
for (let item of this.data.imgList) {
wx.getImageInfo({
src: item,
success: (ress) => {
console.log("获取图片详情", item)
console.log("获取详情成功", ress)
let date = util.formatTime(new Date());
let ctx = wx.createCanvasContext('firstCanvas')
_this.setData({
canvasHeight: ress.height,
canvasWidth: ress.width
})
ctx.drawImage(item, 0, 0, 56, 56)
ctx.setFontSize(30)
ctx.setFillStyle('grey')
ctx.fillText("运联快车", 0, 30)
ctx.strokeText("运联快车", 0, 30)
ctx.draw(false, function () {
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: (res) => {
console.log(res.tempFilePath);
_this.uploadimg(res.tempFilePath);
},
fail: (e) => {
console.log(e)
}
})
})
}
})
}
},
uploadimg(localUrl) {
wx.showLoading({
title: "正在上传图片",
mask: true
})
util.putFile(localUrl).then(res => {
if (res.statusCode == 200) {
wx.hideLoading();
let count = this.data.alreadyUploadSuccessCount;
count = count + 1;
this.setData({
alreadyUploadSuccessCount: count
});
if (count == this.data.uploadimgcount) {
wx.showToast({
title: '图片上传成功',
icon: 'success',
duration: 1000
})
}
if (JSON.parse(res.data).code == 200) {
let uploadObj = JSON.parse(res.data).data;
let arr = []
arr.push(uploadObj)
this.setData({
uploadList: this.data.uploadList.concat(arr)
})
wx.hideLoading();
}
}
})
},