feat(card): 优化卡片页面图片绘制功能

- 修改 loadImg 方法以获取图片的完整信息(路径、宽高)
- 新增 drawImgFill 方法实现 aspectFill 图片绘制模式
- 使用新的图片绘制方法替换原有的 canvas 绘制逻辑
- 改进图片裁剪和填充算法,确保图片不变形且填满指定区域
This commit is contained in:
cg
2026-07-21 06:59:14 +08:00
parent d56788faa4
commit 506f6d2e4e
+18 -3
View File
@@ -136,10 +136,25 @@ export default {
loadImg(src) { loadImg(src) {
return new Promise(r => { return new Promise(r => {
if (!src) return r(null) if (!src) return r(null)
uni.getImageInfo({ src, success: res => r(res.path), fail: () => r(null) }) uni.getImageInfo({
src,
success: res => r({ path: res.path, width: res.width, height: res.height }),
fail: () => r(null)
})
}) })
}, },
// aspectFill 方式绘制图片(居中裁剪填满,不变形)
drawImgFill(ctx, img, dx, dy, dw, dh) {
if (!img) return
const sw = img.width, sh = img.height
if (!sw || !sh) { try { ctx.drawImage(img.path, dx, dy, dw, dh) } catch (e) {} return }
const scale = Math.max(dw / sw, dh / sh)
const cropW = dw / scale, cropH = dh / scale
const sx = (sw - cropW) / 2, sy = (sh - cropH) / 2
try { ctx.drawImage(img.path, sx, sy, cropW, cropH, dx, dy, dw, dh) } catch (e) {}
},
// ===== 海报绘制(醉美夜色风格) ===== // ===== 海报绘制(醉美夜色风格) =====
async drawExportCard() { async drawExportCard() {
const ctx = uni.createCanvasContext('shareCanvas', this) const ctx = uni.createCanvasContext('shareCanvas', this)
@@ -245,7 +260,7 @@ export default {
ctx.save() ctx.save()
this.rr(ctx, P, y, maxW, heroH, 24, 'fill') this.rr(ctx, P, y, maxW, heroH, 24, 'fill')
ctx.clip() ctx.clip()
if (imgs[0]) { try { ctx.drawImage(imgs[0], P, y, maxW, heroH) } catch (e) {} } if (imgs[0]) { this.drawImgFill(ctx, imgs[0], P, y, maxW, heroH) }
else { ctx.setFillStyle(WHITE_05); ctx.fillRect(P, y, maxW, heroH) } else { ctx.setFillStyle(WHITE_05); ctx.fillRect(P, y, maxW, heroH) }
ctx.restore() ctx.restore()
y += heroH + 32 y += heroH + 32
@@ -277,7 +292,7 @@ export default {
ctx.save() ctx.save()
this.rr(ctx, pos.x, pos.y, pos.w, pos.h, 16, 'fill') this.rr(ctx, pos.x, pos.y, pos.w, pos.h, 16, 'fill')
ctx.clip() ctx.clip()
if (imgs[i]) { try { ctx.drawImage(imgs[i], pos.x, pos.y, pos.w, pos.h) } catch (e) {} } if (imgs[i]) { this.drawImgFill(ctx, imgs[i], pos.x, pos.y, pos.w, pos.h) }
else { ctx.setFillStyle(WHITE_05); ctx.fillRect(pos.x, pos.y, pos.w, pos.h) } else { ctx.setFillStyle(WHITE_05); ctx.fillRect(pos.x, pos.y, pos.w, pos.h) }
ctx.restore() ctx.restore()
} }