由于 CanvasContext wx.createCanvasContext 停止维护,

导致微信小程序压缩图片功能提示报错
小程序开发所使用的功能为了避免出现错误,首先通过wx.getImageInfo获取图片信息,之后经过wx.createOffscreenCanvas生成画布,最后生成图片,获取到图片的base64格式地址,通过wx.uploadFile上传后台。具体代码如下


wxml文件内容

<button class="head-img" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
    <image class="avatar" src="{{avatarUrl}}"></image>
</button> 

<canvas canvas-id="canvas" id="mycanvas" type="2d" style="position: absolute;left:-1000px;top:-1000px;"></canvas>

js文件内容

/**
 * 选择头像
 */

onChooseAvatar(e) {
    const that = this
    let avatarUrl = e.detail.avatarUrl
    that.compressImage(avatarUrl, 100)
},

/**
 * 压缩图片
 * imageUrl: 图片地址
 * width:压缩后的图片宽度
 */
compressImage(imageUrl, width) {
    const that = this;
    wx.getImageInfo({
        src: imageUrl,
        success: res => {
            const height = res.height * width / res.width;
            const offscreenCanvas = wx.createOffscreenCanvas({
                type: '2d',
                width,
                height
            })
            const context = offscreenCanvas.getContext('2d')
            const image = offscreenCanvas.createImage()
            image.src = imageUrl;
            image.onload = () => {
                context.clearRect(0, 0, width, height)
                context.drawImage(image, 0, 0, width, height)
                const imageBase64 = offscreenCanvas.toDataURL("image/jpeg", 0.7)
                const base64 = imageBase64.replace(/^data:image\/\w+;base64,/, "")
                that.uploadPic(imageUrl, base64)
            }

        }
    })
},

/**
 * 上传图片 
 */
uploadPic(imgData, base64) {
    const that = this;
    //调用接口上传图片
    let openId = wx.getStorageSync('userOpenid')
    wx.uploadFile({
        url: "https://xxx.xxx.com/upload", // 这里换成你们后端的上传接口即可
        method: 'POST',
        filePath: imgData,
        name: 'file',
        formData: {
            'content': base64   //这里传base64类型
        },
        // 成功回调
        success: (res) => {
            console.log(res)
            let result = JSON.parse(res.data); // JSON.parse()方法是将JSON格式字符串转换为JSON对象
            let newAvatarUrl = result.data; // 返回的图片url
            // 将返回的url替换调默认的url,渲染在页面上
            that.setData({
                avatarUrl: newAvatarUrl
            })
        }
    })
},

MRZYD
145 声望10 粉丝

一个初学的小菜鸟,望各位大佬多多指教