重点:这里必须把canvas挪出屏幕外,而且宽高必须限制,不然显示不出来
changeImage: function (e) {
var that = this;
wx.chooseImage({
sizeType:['original', 'compressed'], //可选择原图或压缩后的图片
sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
success: result => {
wx.getImageInfo({
src: result.tempFilePaths[0],
success: function (res) {
console.log(res.width, res.height)
// that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality);
const windowWidth= wx.getSystemInfoSync().windowWidth;
let imgRatio = res.height/res.width;
that.setData({
cWidth: res.width,
cHeight: windowWidth * imgRatio,
}, () => {
// setData引起的页面渲染完成之后的回调函数
// setData渲染是异步的 canvasToTempFilePath的时候canvas的大小可能还没有被重新设置
that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality);
})
}
})
}
})
},
getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality) {
let query = wx.createSelectorQuery().in(this);
query.select('#myCanvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const image = canvas.createImage();
image.src = tempFilePaths[0];
//新接口需显示设置画布宽高;
canvas.width = canvasWidth
canvas.height = canvasHeight
image.onload = () => {
// 清除Canvas内容
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 在Canvas中绘制图片
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
// 压缩图片
wx.canvasToTempFilePath({
canvas,
fileType: 'jpg', // 可以根据需求修改为其他格式
quality: 0.1, // 压缩质量,范围 0-1
destWidth: canvasWidth,
destHeight: canvasHeight,
success: (res) => {
this.setData({
imagePath: res.tempFilePath,
pic: [res.tempFilePath]
});
console.log('1',res.tempFilePath)
// 压缩后的临时文件路径
// 获取压缩后图片的信息,包括大小等
wx.getFileSystemManager().getFileInfo({
filePath: res.tempFilePath,
success: fileInfo => {
this.setData({
compressSize: fileInfo.size / 1024 / 1024,
cWidth: canvas.width,
// cHeight:canvas.height
})
console.log('压缩后图片大小:', fileInfo.size / 1024 / 1024); // 压缩后图片的大小,单位为字节
console.log('压缩成功',canvas.width, canvas.height)
},
fail: err => {
console.error('获取压缩后图片信息失败:', err);
}
});
},
fail: (err) => {
// 压缩失败处理
console.error('Canvas压缩失败:', err);
wx.showModal({
title: '提示',
content: JSON.stringify(e),
})
}
});
};
})
},