html部分
canvas标签必须写,必须写,后面需要获取canvas的属性
<view style="visibility: hidden;" class="">
<canvas id="updataImg" type="2d" canvas-id="updataImg" class="updataImgCanvar"></canvas>
</view>
js部分
updataImg(){
//从本地选择图片上传
uni.chooseImage({
count: 1, //默认9
sizeType: ['compressed'],
sourceType: ['album'],
success: function (res) {
_this.updating = true //开始上传状态
_this.upImgArr.push(res.tempFilePaths)
_this.compressImage(res.tempFilePaths[0])
}
});
},
compressImage(path) {
uni.getImageInfo({ //获取图片信息
src:path,
success(res) {
let w = res.width, h = res.height, scale = w/h;
w = 960 || w
h = w / scale
const query = uni.createSelectorQuery().in(_this);
let canvas = query.select('#updataImg').fields({ node: true, size: true })
canvas.exec(async (res)=>{
const cvs = res[0].node
cvs.width = w
cvs.height = h
let ctx = cvs.getContext('2d');
const img = cvs.createImage()
await new Promise(resolve => {
img.onload = resolve
img.src = path
})
ctx.drawImage(img, 0, 0, w, h);
let base64 = cvs.toDataURL('image/jpeg', 0.8);
_this.upSingleImg(base64) //开始上传给后端
})
},
fail(err) {
console.log(err)
}
})
},
async upSingleImg(base64){
let data = { responseType:'json' , base64:base64.replace(/\+/g,'%2B')}
const result = await _this.$http.api.pustUpdataImg(data) //接口地址
console.log('上传图片',result)
_this.updating = false //上传结束状态
if(result.error == 0){
_this.resImgArr.push(result.url) //上传成功页面显示
}else{
_this.upImgArr.splice(_this.upImgArr.length-1,1) //上传失败,页面自动删除
}
},
需要注意的是获取canvas元素时的这个
fields({ node: true, size: true })
是必须加入的,不然后面所需要的参数值是无法获取到