创建一个canvas元素(id为checkCanvas),获取对应的上下文对象,并设置图片宽高最大不能超过120,代码如下:const SIZE = 120 const ratio = Math.max(imgInfo.width / SIZE, imgInfo.height / SIZE, 1) const smallWidth = Math.trunc(imgInfo.width / ratio) const smallHeight = Math.trunc(imgInfo.height / ratio) // 将宽高大小设置到页面的canvas元素(checkCanvas)上 this.smallWidth = smallWidth this.smallHeight = smallHeight const ctx = wx.createCanvasContext('checkCanvas') ctx.drawImage(imgInfo.path, 0, 0, smallWidth, smallHeight) ctx.draw(false, function () { setTimeout(() => { wx.canvasToTempFilePath({ canvasId: 'checkCanvas', width: smallWidth, height: smallHeight, destWidth: smallWidth, destHeight: smallHeight, success: (res) => { resolve(res.tempFilePath) }, fail: (e) => { reject(e) } }) }, 100) }),怎么按照上面的步骤结合 addPic: function () { wx.chooseImage({ sizeType: ['compressed'], success: (imgRes) => { wx.getImageInfo({ src: imgRes.tempFilePaths[0], success: async (imgInfo) => { callBack && callBack(imgInfo); }, fail: () => {}, }); }, fail: () => {}, }) }进行操作
时间: 2024-01-07 19:05:47 浏览: 170
好的,我可以帮你将这段代码添加到addPic函数中。你需要在addPic函数中添加以下代码:
```
addPic: function (callBack) {
wx.chooseImage({
sizeType: ['compressed'],
success: (imgRes) => {
wx.getImageInfo({
src: imgRes.tempFilePaths[0],
success: async (imgInfo) => {
const SIZE = 120
const ratio = Math.max(imgInfo.width / SIZE, imgInfo.height / SIZE, 1)
const smallWidth = Math.trunc(imgInfo.width / ratio)
const smallHeight = Math.trunc(imgInfo.height / ratio)
const ctx = wx.createCanvasContext('checkCanvas')
ctx.drawImage(imgInfo.path, 0, 0, smallWidth, smallHeight)
ctx.draw(false, function () {
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'checkCanvas',
width: smallWidth,
height: smallHeight,
destWidth: smallWidth,
destHeight: smallHeight,
success: (res) => {
callBack && callBack(res.tempFilePath)
},
fail: (e) => {
console.log(e)
}
})
}, 100)
})
},
fail: () => {},
});
},
fail: () => {},
})
}
```
这样,当你调用addPic函数时,它将会选择一张图片,然后将图片压缩至宽高最大不能超过120,并将其绘制到名为“checkCanvas”的canvas元素上,最后将canvas元素转换为临时文件路径并返回给回调函数。
阅读全文
相关推荐














