uniapp写了一个把图片转成canvas来实现固定尺寸的方法报错?
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"
回复
1个回答
test
2024-06-30
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)
}
});
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容