- 直接上代码
<view bindtap='uploadImg'>上传</view>
<canvas style="width: {{cw}}px; height: {{ch}}px;" canvas-id="firstCanvas"></canvas>
<button bindtap="seeImg">预览</button>
const app = getApp()
Page({
data: {
uploadPic:[],
cw:0,
ch:0
},
uploadImg(e) {
let that = this;
wx.chooseImage({
success(res) {
var tempFilePaths=res.tempFilePaths
wx.getImageInfo({
src: res.tempFilePaths[0],
success(res) {
var originWidth=res.height, originHeight= res.width;
var maxWidth = 200,maxHeight = 200;
var targetWidth = originWidth,targetHeight = originHeight;
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > maxWidth / maxHeight) {
targetWidth = maxWidth;
targetHeight = Math.round(maxWidth * (originHeight / originWidth));
} else {
targetHeight = maxHeight;
targetWidth = Math.round(maxHeight * (originWidth / originHeight));
}
}
var ctx = wx.createCanvasContext('firstCanvas');
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight);
ctx.draw();
that.setData({
cw: targetWidth,
ch: targetHeight
});
setTimeout(function() {
wx.canvasToTempFilePath({
canvasId: 'firstCanvas',
success: (res) => {
wx.uploadFile({
url: 'https://res.liketon.cn/api/Img?type=image&group=fingertip',
filePath: res.tempFilePath,
name: 'file',
success(res) {
let data = JSON.parse(res.data)
that.setData({
uploadpic:[data.data[0]]
})
}
})
},
fail: (err) => {
console.error(err)
}
}, this)
}, 500);
}
})
}
})
},
seeImg(){
wx.previewImage({
current: this.data.uploadpic[0],
urls: this.data.uploadpic
})
},
})