export const cropImage = (filePath:string): Promise<string> => { return new Promise((resolve, reject) => { uni.getImageInfo({ src: filePath, success(res) { let sx, sy, sw, sh, imgRatio, canvasRatio; const ctx = uni.createCanvasContext('canvas', this); canvasRatio = 2/3 imgRatio = res.width / res.height if(imgRatio <= canvasRatio){ sw = 1200 sh = sw / canvasRatio sx = 0 sy = (res.height - sh) / 2 } else{ sh = 1800 sw = sh * canvasRatio sx = (res.width - sw) / 2 sy = 0 } ctx.drawImage(res.path, sx, sy, sw, sh, 0, 0, 1200, 1800); // @ts-ignore ctx.draw(false, setTimeout(() => { uni.canvasToTempFilePath({ canvasId: 'canvas', success: (res) => { resolve(res.tempFilePath) }, fail: (error) => { console.log('error', error); reject('') } }, this) }, 500)) }, fail() { reject('') } }) }) }
我的项目有个功能选择相册中的一张图片,给他转成固定的尺寸。写完之后发现uni.canvasToTempFilePath总是报这个错误,不知道是哪里出现了问题?
<script lang="ts" setup> import { ref } from 'vue' // @ts-ignore import { useUser } from '@/stores/app' import { cropImage } from '@/utils/index' const user = useUser() const imgs = ref<string []>([]) user.photo.forEach(async item => { imgs.value.push(await cropImage(item.path as string)); })
errMsg: “canvasToTempFilePath:fail fail canvas is empty”
export const cropImage = (filePath:string, context:any): Promise<string> => { return new Promise((resolve, reject) => { uni.getImageInfo({ src: filePath, success(res) { let sx, sy, sw, sh, imgRatio, canvasRatio; const ctx = uni.createCanvasContext('canvas', context); canvasRatio = 2/3 imgRatio = res.width / res.height if(imgRatio <= canvasRatio){ sw = 1200 sh = sw / canvasRatio sx = 0 sy = (res.height - sh) / 2 } else{ sh = 1800 sw = sh * canvasRatio sx = (res.width - sw) / 2 sy = 0 } ctx.drawImage(res.path, sx, sy, sw, sh, 0, 0, 1200, 1800); ctx.draw(false, setTimeout(() => { uni.canvasToTempFilePath({ canvasId: 'canvas', success: (res) => { resolve(res.tempFilePath) }, fail: (error) => { console.log('error', error); reject('') } }, context) }, 500)) }, fail() { reject('') } }) }) } let that = this; uni.chooseImage({ sourceType: ['album'], success (res) { cropImage(res.tempFiles[0].path, that) } });