這里注意一下,圖片壓縮后的寬度是畫布寬度的一半
canvasToTempFilePath 創建畫布的時候會有一定的時間延遲容易失敗,這里加setTimeout來緩沖一下
這是單張圖片壓縮,多張的壓縮暫時還沒有成功,保存到服務器上后是空白的,如有大神望指點一二(>人<;)
<canvas canvas-id='photo_canvas' style='width:1000rpx;height:{{canvas_h}}px' class='myCanvas'></canvas>
/**壓縮圖片 */
compressionImage(tempFilePaths, params) {
let that = this
wx.getImageInfo({
src: tempFilePaths[0],
success: function(res) {
var ctx = wx.createCanvasContext('photo_canvas');
//設置canvas尺寸
var towidth = 500; //按寬度500px的比例壓縮
var toheight = Math.trunc(500 * res.height / res.width);
that.setData({
canvas_h: toheight
})
ctx.drawImage(tempFilePaths[0], 0, 0, res.width, res.height, 0, 0, towidth, toheight)
that.createMap(ctx, params);
}
})
},
/**創建畫布並上傳圖片 */
createMap(ctx, params) {
let that = this;
ctx.draw(true, function() {
wx.showLoading({
title: '壓縮中',
})
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'photo_canvas',
fileType: "jpg",
success: function(res) {
wx.hideLoading();
wx.uploadFile({
url: app.globalData.baseUrl + '/wechat/want/addWant',
filePath: res.tempFilePath,
name: 'file',
formData: {
'parameters': JSON.stringify(params)
},
success: function(res) {
console.log("state:" + JSON.parse(res.data).state)
if (JSON.parse(res.data).state === 1) {
wx.showToast({
title: '發布成功',
duration: 2000,
icon: "none",
success() {
setTimeout(function() {
wx.navigateBack({
delta: 1,
})
}, 1000);
}
})
}
},
fail(res) {
console.log("fail" + res)
}
})
},
fail(res) {
if (res.errMsg === "canvasToTempFilePath:fail:create bitmap failed") {
console.log("導出map失敗")
}
}
}, this)
}, 200);
})
},