没啥可说的,直接看代码吧(邪恶的微信小程序和浏览器的还不一样)
//将用户图片自动剪切成正方形
const cutImgToSquare = (imgPath: string) => {//@ts-ignorewx.createSelectorQuery().select('#canvas').fields({ node: true, size: true }).exec((res: any) => {const canvas = res[0].nodeconst ctx = canvas.getContext('2d')const image = canvas.createImage()image.onload = () => {const size = Math.min(image.width, image.height)canvas.width = sizecanvas.height = sizectx.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-ignorewx.canvasToTempFilePath({canvas,success: (res: any) => {console.log("调用成功", res)},fail: (err: any) => {console.log("调用失败", err)loading.value = falseuni.showToast({title: '图片上传失败!',icon: 'error'})},complete: (res: any) => {console.log("调用完成", res)}})}image.src = imgPath})
}
这里在wx.canvasToTempFilePath中的success中的返回值就是截取后的图片临时地址