微信小程序中将图片截图为正方形(自动居中)

没啥可说的,直接看代码吧(邪恶的微信小程序和浏览器的还不一样)

TypeScript 复制代码
//将用户图片自动剪切成正方形
const cutImgToSquare = (imgPath: string) => {
    //@ts-ignore
    wx.createSelectorQuery()
        .select('#canvas')
        .fields({ node: true, size: true })
        .exec((res: any) => {
            const canvas = res[0].node
            const ctx = canvas.getContext('2d')
            const image = canvas.createImage()
            image.onload = () => {
                const size = Math.min(image.width, image.height)
                canvas.width = size
                canvas.height = size
                ctx.clearRect(0, 0, canvas.width, canvas.height)
                ctx.drawImage(image, (image.width - size) / 2, (image.height - size) / 2, size, size, 0, 0, size, size)
                //@ts-ignore
                wx.canvasToTempFilePath({
                    canvas,
                    success: (res: any) => {
                        console.log("调用成功", res)
                    },
                    fail: (err: any) => {
                        console.log("调用失败", err)
                        loading.value = false
                        uni.showToast({
                            title: '图片上传失败!',
                            icon: 'error'
                        })
                    },
                    complete: (res: any) => {
                        console.log("调用完成", res)
                    }
                })
            }
            image.src = imgPath
        })
}

这里在wx.canvasToTempFilePath中的success中的返回值就是截取后的图片临时地址

相关推荐
embedded大铭6 小时前
ai时代上站记录
typescript
单词记忆方法研究6 小时前
探索上海背单词小程序品牌:高效学习工具的优化之路
大数据·学习·小程序
码上成长7 小时前
小程序请求层怎么封装?
前端·小程序
万岳科技系统开发7 小时前
医疗诊所小程序如何实现患者管理和会员运营?
java·小程序·apache
用户9385156350719 小时前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformers.js 全链路实战(三)
前端·react.js·typescript
java1234_小锋20 小时前
【免费】基于Python的微信小程序网约车(打车,在线叫车,移动出行)系统(FastAPI+Vue3) 锋哥原创出品,必属精品
微信小程序·小程序·fastapi·网约车系统·在线叫车系统
执子念的飞鱼1 天前
File Viewer 进入 2K 节点后,我更在意这 3 条回归
前端·typescript
mONESY1 天前
TypeScript 面试高频:type 与 interface 到底怎么选?
typescript
2501_916007471 天前
Bundle ID 注册与管理 App ID 创建指南 命名规则 权限开关与删除注意事项
android·ios·小程序·https·uni-app·iphone·webview
meilindehuzi_a1 天前
TypeScript面试题:interface 与 type:相同点、核心区别与选择指南
java·ubuntu·typescript