需在 wxml 中加入 canvas 組件,可設置 hidden 作為容器
<canvas canvas-id='pickImg' class="upload" hidden></canvas>
在 js 中控制 canvas 繪制圖片
export function imgUpload(callback){ wx.chooseImage({ count: 1, // 默認9 sizeType: ['compressed'], // 'original', 'compressed' sourceType: ['album', 'camera'], success: (res) => { // console.log(res) res.tempFiles.map(i=>{ let size = i.size if (size > 1 * 1024 * 1024) { return wx.showToast({ title: '圖片過大', icon: 'none' }) }else{ toCanvas(i.path, callback) } }) } }) } function toCanvas(file,callback){ wx.showLoading({ title: '加載中' }) let temp = file // canvasId 提前定義 let canvas = wx.createCanvasContext(canvasId) // 獲取設備系統 const platform = wx.getSystemInfoSync().platform wx.getImageInfo({ src: temp, success: res => { let imgWidth = res.width> 750 ? 750 : res.width let imgHeight = imgWidth * res.height/ res.width canvas.drawImage(temp, 0, 0, imgWidth, imgHeight) canvas.draw(false, () => { let temp_path = '' wx.canvasToTempFilePath({ x: 0, y: 0, width: imgWidth, height: imgHeight, destWidth: imgWidth *2, destHeight: imgHeight *2, canvasId, success: function (res) { // console.log(res.tempFilePath) temp_path = res.tempFilePath // 小程序讀取文件管理器 api let fileSystemManager = wx.getFileSystemManager() fileSystemManager.readFile({ filePath: temp_path, encoding: 'base64', success: (data)=>{ // console.log(data) let base64 = 'data:image/png;base64,'+data // 自定義接口 let { promise } = http.imgUpload( base64 ) promise.then(resolve=>{ console.log(resolve) callback && callback(filePath, temp_path) wx.hideLoading() }) } }) } }) }) }, fail:(e)=>{ console.log('getImageInfo error:',e) wx.hideLoading() } }) }