# 使用canvas绘制图片后实现图片压缩功能(约15~20倍压缩)后上传图片
html中要存在id与js中相同的模块占位:
js代码如下:
/* canvas绘图实现压缩 */
toCanvas(src, type = 1) {// 第二个参数区分正反面:正面人像-1;反面国徽-0;
const that = this;
const { windowWidth, windowHeight, pixelRatio } = wx.getSystemInfoSync();
const maxSize = 750;
wx.getImageInfo({
src,
success: res1 => {
// const ratio = res1.width / res1.height;
let width = res1.width;
let height = res1.height;
const maxWidth = windowWidth;
const maxHeight = windowHeight;
let ratio = 0;
// 如果图片宽度或高度超过最大值,则按比例缩小图片
if (width > maxWidth || height > maxHeight) {
ratio = Math.min(maxWidth / width, maxHeight / height);
width *= ratio;
height *= ratio;
}
let query = wx.createSelectorQuery()
query.select(`#mycanvas`).fields({ node: true, size: true }).exec((res2) => {
console.log(res2, 'node-----');
let canvas = res2[0].node
let ctx = canvas.getContext('2d')
let pic = canvas.createImage()
canvas.width = width;
canvas.height = height;
// ctx.fillRect(0, 0, canvas.width, canvas.height);
pic.src = src
pic.onload = () => {
ctx.drawImage(pic, 0, 0, width, height)
}
// console.log('canvas==', canvas);
setTimeout(() => {
// console.log(canvas.toDataURL('image/jpg', 0.9))
// 第二个参数区分正反面:正面人像-1;反面国徽-0;
that.uploadImg(canvas.toDataURL('image/jpg', 0.9), type)
}, 1000);
})
}
})
},
/* 2023-08-24最新上传图片 */
uploadImg(url, type = 1) { // 第二个参数区分正反面:正面人像-01;反面国徽-00;
const that = this;
const realName = wx.getStorageSync('memId') + '_0' + type + '.png';
const params = {
imgName: realName,
imgBase64: url,
}
wx.request({
url: baseUrl + 'open/uploadPhotosBase64',
data: params,
method: 'POST',
success: res => {
console.log(res);
if (res.statusCode == '200') {
console.log('base64上传服务器后的图片地址--', res.data.file);
let photo = type == 1 ? 'idcardzm' : 'idcardfm'
that.setData({
[photo]: res.data.file,
})
}
}
})
console.log(params);
},