feat: 宠物身份卡(canvas 绘制 + 小程序码 + 存相册/分享)
竞品那张「居民身份卡」,完整做了。 ## 后端 service/wxacode.go —— 小程序码。两步:先拿 access_token(2h 有效,进程内缓存、 提前 5 分钟过期),再调 getwxacodeunlimit 换一张 PNG 存到 MinIO 返回 URL。 同一只宠物的码 object 名按 pet id 定死,存在就直接返回不重新生成 —— 微信侧有日调用配额,不能每次点都烧一次。 ⚠️ getwxacodeunlimit 要求 page 在**已发布**的小程序版本里。开发/未发布时返回 errcode 41030,实测确认。这时身份卡照常出、只是没码(qr_ready=false), 发布后自动就有,不用改代码。best-effort,取不到不算错。 service/idcard.go —— 组装卡片内容。身份 ID 用「宠物雪花 id 的数字 + 生日」 拼成 18 位、每 4 位空一下,纯装饰不入库不校验,同一只每次都一样。 介绍按物种给默认(汪星人/喵星人来地球啦~)。有效期用生日起算。 GET /api/pets/:id/id-card storage 加了 Exists(StatObject),生成前先查。 ## 前端 pages/idcard 离屏 canvas 2d 画卡,导出成图展示 + 存相册 + 分享(open-type=share, imageUrl 用画好的卡当封面)。 两张远程图(头像 + 小程序码)都用 node.createImage() 异步加载, **Promise.all 等两张都就绪再开画** —— 否则小程序码会画不上或画一半 (规划里专门点过名的坑)。任一张加载失败 resolve(null),缺图也照画: 头像缺→画物种 emoji,码缺→画「小程序码 待发布」占位框。 存相册的权限被拒过一次后 wx.authorize 不再弹,走 openSetting 引导(同海报那套)。 绘制复用了 bottom-sheet 里 poster 的 canvas 模式(dpr 放大、roundRect、 canvasToTempFilePath),但 poster 只画文字不画远程图,这里的双图加载是新写的。 入口:「我的」→ 身份卡,用当前选中的宠物。 ## 验证(预生产库实跑) id-card 接口返回:姓名/性别/品种/生日/介绍/身份ID/有效期 全对 身份 ID = 3410 4333 1420 2503 17(宠物id数字+生日,稳定) qr_ready = false,日志确认 41030 invalid page(小程序未发布,预期) canvas 版式用 HTML 复刻确认过:未发布=占位、发布后=真码 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -195,3 +195,13 @@ func (h *Handler) PetStageDrift(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
response.OK(c, h.svc.CheckStageDrift(pet))
|
response.OK(c, h.svc.CheckStageDrift(pet))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PetIDCard GET /api/pets/:id/id-card 宠物身份卡内容(含小程序码,未发布时无码)
|
||||||
|
func (h *Handler) PetIDCard(c *gin.Context) {
|
||||||
|
card, err := h.svc.GetIDCard(middleware.UserID(c), idParam(c, "id"))
|
||||||
|
if err != nil {
|
||||||
|
respondErr(c, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
response.OK(c, card)
|
||||||
|
}
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ func registerUserAPI(api *gin.RouterGroup, h *handler.Handler, jm *appjwt.Manage
|
|||||||
g.GET("/pets/:id/plan", h.GetPlan)
|
g.GET("/pets/:id/plan", h.GetPlan)
|
||||||
g.GET("/pets/:id/plan/calendar", h.PlanCalendar)
|
g.GET("/pets/:id/plan/calendar", h.PlanCalendar)
|
||||||
g.GET("/pets/:id/stage-drift", h.PetStageDrift)
|
g.GET("/pets/:id/stage-drift", h.PetStageDrift)
|
||||||
|
g.GET("/pets/:id/id-card", h.PetIDCard)
|
||||||
g.GET("/pets/:id/plan/month-status", h.PlanMonthStatus)
|
g.GET("/pets/:id/plan/month-status", h.PlanMonthStatus)
|
||||||
// 养护方案:列出可选的、套用一套到某个月
|
// 养护方案:列出可选的、套用一套到某个月
|
||||||
g.GET("/care-templates", h.CareTemplateOptions)
|
g.GET("/care-templates", h.CareTemplateOptions)
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/sundynix/pets-be/internal/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IDCard 宠物身份卡的全部内容,前端拿去 canvas 上画
|
||||||
|
type IDCard struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Species string `json:"species"` // 猫猫 / 狗狗
|
||||||
|
Gender string `json:"gender"`
|
||||||
|
Breed string `json:"breed"`
|
||||||
|
Birthday string `json:"birthday"` // "2023 年 12 月 15 日"
|
||||||
|
Intro string `json:"intro"`
|
||||||
|
AvatarURL string `json:"avatar_url"`
|
||||||
|
IDNo string `json:"id_no"` // 玩具身份号,不入库
|
||||||
|
Validity string `json:"validity"` // "2023.12.15 - 永远"
|
||||||
|
QRURL string `json:"qr_url"` // 小程序码,未发布时为空
|
||||||
|
QRReady bool `json:"qr_ready"` // 码有没有生成出来
|
||||||
|
}
|
||||||
|
|
||||||
|
// petIDNo 造一个稳定的「身份号」。纯装饰,不入库、不做校验。
|
||||||
|
// 规律照竞品那种:一串数字,扫不出真实含义但看着像证件号。
|
||||||
|
// 用 宠物雪花 id 的数字 + 生日 拼,同一只宠物每次都一样
|
||||||
|
func petIDNo(pet *model.Pet) string {
|
||||||
|
digits := make([]byte, 0, 18)
|
||||||
|
for i := 0; i < len(pet.ID) && len(digits) < 10; i++ {
|
||||||
|
if pet.ID[i] >= '0' && pet.ID[i] <= '9' {
|
||||||
|
digits = append(digits, pet.ID[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for len(digits) < 10 {
|
||||||
|
digits = append(digits, '0')
|
||||||
|
}
|
||||||
|
bd := "00000000"
|
||||||
|
if pet.Birthday != nil && !pet.Birthday.IsZero() {
|
||||||
|
bd = pet.Birthday.Format("20060102")
|
||||||
|
}
|
||||||
|
raw := string(digits[:10]) + bd // 18 位
|
||||||
|
// 每 4 位空一下,像证件号
|
||||||
|
var b strings.Builder
|
||||||
|
for i, c := range raw {
|
||||||
|
if i > 0 && i%4 == 0 {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
}
|
||||||
|
b.WriteRune(c)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetIDCard 组装身份卡。小程序码是 best-effort:拿不到(未发布/配额)也照出卡
|
||||||
|
func (s *Service) GetIDCard(userID, petID string) (*IDCard, error) {
|
||||||
|
pet, err := s.GetPet(userID, petID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
intro := "地球来了个新居民~"
|
||||||
|
switch pet.Type {
|
||||||
|
case "狗狗":
|
||||||
|
intro = "汪星人来地球啦~"
|
||||||
|
case "猫猫":
|
||||||
|
intro = "喵星人来地球啦~"
|
||||||
|
}
|
||||||
|
|
||||||
|
bd, validity := "未知", "永久有效"
|
||||||
|
if pet.Birthday != nil && !pet.Birthday.IsZero() {
|
||||||
|
bd = pet.Birthday.Format("2006 年 1 月 2 日")
|
||||||
|
validity = pet.Birthday.Format("2006.01.02") + " - 永远"
|
||||||
|
}
|
||||||
|
|
||||||
|
card := &IDCard{
|
||||||
|
Name: pet.Name, Species: pet.Type, Gender: pet.Gender, Breed: pet.Breed,
|
||||||
|
Birthday: bd, Intro: intro, AvatarURL: pet.AvatarURL,
|
||||||
|
IDNo: petIDNo(pet), Validity: validity,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 小程序码取不到不算错——未发布/配额用尽时卡照样出,只是没码
|
||||||
|
if url, e := s.PetQRCode(petID); e == nil {
|
||||||
|
card.QRURL = url
|
||||||
|
card.QRReady = true
|
||||||
|
} else {
|
||||||
|
log.Printf("[info] 宠物 %s 的小程序码暂不可用(多为小程序未发布):%v", petID, e)
|
||||||
|
}
|
||||||
|
return card, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 小程序码(wxacode)。身份卡右下角那个码,扫了能进小程序。
|
||||||
|
//
|
||||||
|
// 两步:先拿 access_token(有 2h 有效期,缓存复用),再调 getwxacodeunlimit
|
||||||
|
// 换一张 PNG,存到 MinIO 返回 URL。同一只宠物的码存一次就够——微信侧有
|
||||||
|
// 日调用配额,object 名按宠物 id 定死,存在就直接返回不重新生成。
|
||||||
|
//
|
||||||
|
// ⚠️ getwxacodeunlimit 要求 page 存在于**已发布**的小程序版本里。开发版/未发布
|
||||||
|
// 时会返回 errcode 41030(page 不存在),这时身份卡照常出,只是没有码。
|
||||||
|
// 发布之后自动就有了,不用改代码。
|
||||||
|
|
||||||
|
// accessToken 缓存。进程级,够用——多实例各自缓存不影响正确性
|
||||||
|
var (
|
||||||
|
atMu sync.Mutex
|
||||||
|
atValue string
|
||||||
|
atExpires time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
// wechatAccessToken 取 access_token,带缓存。提前 5 分钟过期,避免边界上用到失效的
|
||||||
|
func (s *Service) wechatAccessToken() (string, error) {
|
||||||
|
atMu.Lock()
|
||||||
|
defer atMu.Unlock()
|
||||||
|
if atValue != "" && time.Now().Before(atExpires) {
|
||||||
|
return atValue, nil
|
||||||
|
}
|
||||||
|
if s.cfg.WeChat.AppID == "" || s.cfg.WeChat.AppSecret == "" {
|
||||||
|
return "", errors.New("微信 app_id / app_secret 未配置")
|
||||||
|
}
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("grant_type", "client_credential")
|
||||||
|
q.Set("appid", s.cfg.WeChat.AppID)
|
||||||
|
q.Set("secret", s.cfg.WeChat.AppSecret)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, http.MethodGet,
|
||||||
|
"https://api.weixin.qq.com/cgi-bin/token?"+q.Encode(), nil)
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var out struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
ErrCode int `json:"errcode"`
|
||||||
|
ErrMsg string `json:"errmsg"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if out.AccessToken == "" {
|
||||||
|
return "", fmt.Errorf("拿 access_token 失败(%d): %s", out.ErrCode, out.ErrMsg)
|
||||||
|
}
|
||||||
|
atValue = out.AccessToken
|
||||||
|
atExpires = time.Now().Add(time.Duration(out.ExpiresIn-300) * time.Second)
|
||||||
|
return atValue, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PetQRCode 取某只宠物的小程序码 URL。存在就直接返回,不存在才向微信换。
|
||||||
|
// scene 里带宠物 id,扫码进来时小程序能拿到(暂时只用来打开小程序)
|
||||||
|
func (s *Service) PetQRCode(petID string) (string, error) {
|
||||||
|
if s.storage == nil {
|
||||||
|
return "", errors.New("对象存储未配置")
|
||||||
|
}
|
||||||
|
obj := "wxacode/" + petID + ".png"
|
||||||
|
if s.storage.Exists(obj) {
|
||||||
|
return s.storage.PublicURL(obj), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := s.wechatAccessToken()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
body, _ := json.Marshal(map[string]any{
|
||||||
|
"scene": "pet=" + petID, // 最长 32 字符,够放一个雪花 id
|
||||||
|
"page": "pages/home/home",
|
||||||
|
"check_path": true,
|
||||||
|
"width": 280,
|
||||||
|
})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
req, _ := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||||
|
"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token, bytes.NewReader(body))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
// 成功返回图片二进制;失败返回一段 JSON。用 Content-Type 分辨最稳
|
||||||
|
if ct := resp.Header.Get("Content-Type"); len(ct) >= 5 && ct[:5] == "image" {
|
||||||
|
if _, err := s.storage.Upload(obj, bytes.NewReader(data), int64(len(data)), "image/png"); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return s.storage.PublicURL(obj), nil
|
||||||
|
}
|
||||||
|
var e struct {
|
||||||
|
ErrCode int `json:"errcode"`
|
||||||
|
ErrMsg string `json:"errmsg"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(data, &e)
|
||||||
|
// 41030 = page 不在已发布版本里。开发期常见,往上层透传让它降级
|
||||||
|
return "", fmt.Errorf("微信生成小程序码失败(%d): %s", e.ErrCode, e.ErrMsg)
|
||||||
|
}
|
||||||
@@ -92,6 +92,15 @@ func (s *Storage) Upload(objectName string, reader io.Reader, size int64, conten
|
|||||||
return s.PublicURL(objectName), nil
|
return s.PublicURL(objectName), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Exists 对象在不在。小程序码有微信侧配额,同一只宠物的码存一次就够,
|
||||||
|
// 生成前先查
|
||||||
|
func (s *Storage) Exists(objectName string) bool {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_, err := s.client.StatObject(ctx, s.bucket, objectName, minio.StatObjectOptions{})
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
// PublicURL 由对象名拼出可访问 URL(用当前配置的 public_base_url,避免存旧地址)
|
// PublicURL 由对象名拼出可访问 URL(用当前配置的 public_base_url,避免存旧地址)
|
||||||
func (s *Storage) PublicURL(objectName string) string {
|
func (s *Storage) PublicURL(objectName string) string {
|
||||||
return fmt.Sprintf("%s/%s/%s", s.publicBaseURL, s.bucket, objectName)
|
return fmt.Sprintf("%s/%s/%s", s.publicBaseURL, s.bucket, objectName)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"pages/history/history",
|
"pages/history/history",
|
||||||
"pages/expense/expense",
|
"pages/expense/expense",
|
||||||
"pages/petform/petform",
|
"pages/petform/petform",
|
||||||
|
"pages/idcard/idcard",
|
||||||
"pages/report/report",
|
"pages/report/report",
|
||||||
"pages/community/community",
|
"pages/community/community",
|
||||||
"pages/learn/learn",
|
"pages/learn/learn",
|
||||||
|
|||||||
@@ -0,0 +1,263 @@
|
|||||||
|
const store = require('../../utils/store.js');
|
||||||
|
const api = require('../../utils/api.js');
|
||||||
|
const { toastErr } = require('../../utils/ui.js');
|
||||||
|
|
||||||
|
// 卡片画布尺寸(逻辑像素)。真实导出会按 dpr 放大
|
||||||
|
const W = 620;
|
||||||
|
const H = 760;
|
||||||
|
|
||||||
|
// 在 canvas 2d 上加载一张图(远程或本地),resolve 出可直接 drawImage 的 image 对象。
|
||||||
|
// 加载失败 resolve(null)——头像或小程序码缺一张不该让整张卡画不出来
|
||||||
|
function loadImage(canvas, src) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (!src) return resolve(null);
|
||||||
|
const img = canvas.createImage();
|
||||||
|
img.onload = () => resolve(img);
|
||||||
|
img.onerror = () => resolve(null);
|
||||||
|
img.src = src;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Page({
|
||||||
|
data: {
|
||||||
|
petId: '',
|
||||||
|
card: null,
|
||||||
|
cardImg: '',
|
||||||
|
qrReady: false,
|
||||||
|
saving: false,
|
||||||
|
},
|
||||||
|
onLoad(q) {
|
||||||
|
store
|
||||||
|
.ready()
|
||||||
|
.then(() => {
|
||||||
|
const id = (q && q.id) || store.currentPetId();
|
||||||
|
if (!id) {
|
||||||
|
wx.showToast({ title: '先选一只毛孩子', icon: 'none' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.setData({ petId: id });
|
||||||
|
return api.petIDCard(id);
|
||||||
|
})
|
||||||
|
.then((card) => {
|
||||||
|
if (!card) return;
|
||||||
|
this.setData({ card, qrReady: !!card.qr_ready });
|
||||||
|
// 布局要等页面渲染完 canvas 节点才拿得到,放 nextTick
|
||||||
|
wx.nextTick(() => this.draw());
|
||||||
|
})
|
||||||
|
.catch((e) => toastErr(e));
|
||||||
|
},
|
||||||
|
|
||||||
|
draw() {
|
||||||
|
wx.createSelectorQuery()
|
||||||
|
.select('#idCanvas')
|
||||||
|
.fields({ node: true, size: true })
|
||||||
|
.exec((res) => {
|
||||||
|
const node = res && res[0] && res[0].node;
|
||||||
|
if (!node) return;
|
||||||
|
let dpr = 2;
|
||||||
|
try {
|
||||||
|
dpr = (wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync()).pixelRatio || 2;
|
||||||
|
} catch (e) {
|
||||||
|
dpr = 2;
|
||||||
|
}
|
||||||
|
node.width = W * dpr;
|
||||||
|
node.height = H * dpr;
|
||||||
|
const ctx = node.getContext('2d');
|
||||||
|
ctx.scale(dpr, dpr);
|
||||||
|
|
||||||
|
const c = this.data.card || {};
|
||||||
|
// 两张远程图都就绪再开画,否则小程序码会画不上或画一半(plan 里点过名的坑)
|
||||||
|
Promise.all([loadImage(node, c.avatar_url), loadImage(node, c.qr_url)]).then(([avatar, qr]) => {
|
||||||
|
this.paint(ctx, node, c, avatar, qr);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
paint(ctx, node, c, avatar, qr) {
|
||||||
|
ctx.clearRect(0, 0, W, H);
|
||||||
|
|
||||||
|
// 外层留白背景
|
||||||
|
ctx.fillStyle = '#F3EFE8';
|
||||||
|
ctx.fillRect(0, 0, W, H);
|
||||||
|
|
||||||
|
const pad = 30;
|
||||||
|
const cardW = W - pad * 2;
|
||||||
|
|
||||||
|
// ── 上半张:资料区(蓝紫渐变)──
|
||||||
|
const topH = 380;
|
||||||
|
const g1 = ctx.createLinearGradient(pad, pad, W - pad, topH);
|
||||||
|
g1.addColorStop(0, '#FFF0D6');
|
||||||
|
g1.addColorStop(0.5, '#FFE0EC');
|
||||||
|
g1.addColorStop(1, '#E6EEFF');
|
||||||
|
this.roundRect(ctx, pad, pad, cardW, topH - pad, 28);
|
||||||
|
ctx.fillStyle = g1;
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// 头像圆
|
||||||
|
const avX = pad + 34, avY = pad + 34, avD = 108;
|
||||||
|
ctx.save();
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(avX + avD / 2, avY + avD / 2, avD / 2, 0, Math.PI * 2);
|
||||||
|
ctx.closePath();
|
||||||
|
ctx.clip();
|
||||||
|
if (avatar) {
|
||||||
|
ctx.drawImage(avatar, avX, avY, avD, avD);
|
||||||
|
} else {
|
||||||
|
ctx.fillStyle = '#FFD9A3';
|
||||||
|
ctx.fillRect(avX, avY, avD, avD);
|
||||||
|
ctx.fillStyle = '#8A5A18';
|
||||||
|
ctx.font = '52px sans-serif';
|
||||||
|
ctx.textAlign = 'center';
|
||||||
|
ctx.textBaseline = 'middle';
|
||||||
|
ctx.fillText(c.species === '狗狗' ? '🐶' : '🐱', avX + avD / 2, avY + avD / 2);
|
||||||
|
}
|
||||||
|
ctx.restore();
|
||||||
|
ctx.textBaseline = 'alphabetic';
|
||||||
|
|
||||||
|
// 资料行
|
||||||
|
const infoX = avX + avD + 28;
|
||||||
|
let y = pad + 52;
|
||||||
|
const line = (label, value) => {
|
||||||
|
ctx.textAlign = 'left';
|
||||||
|
ctx.font = '24px sans-serif';
|
||||||
|
ctx.fillStyle = '#9A8F82';
|
||||||
|
ctx.fillText(label, infoX, y);
|
||||||
|
ctx.fillStyle = '#2D2925';
|
||||||
|
ctx.font = '600 26px sans-serif';
|
||||||
|
ctx.fillText(value || '—', infoX + ctx.measureText(label).width + 14, y);
|
||||||
|
y += 46;
|
||||||
|
};
|
||||||
|
line('姓名', c.name);
|
||||||
|
// 性别 + 品种放一行
|
||||||
|
ctx.textAlign = 'left';
|
||||||
|
ctx.font = '24px sans-serif';
|
||||||
|
ctx.fillStyle = '#9A8F82';
|
||||||
|
ctx.fillText('性别', infoX, y);
|
||||||
|
ctx.fillStyle = '#2D2925';
|
||||||
|
ctx.font = '600 26px sans-serif';
|
||||||
|
const gw = ctx.measureText(c.gender || '—').width;
|
||||||
|
ctx.fillText(c.gender || '—', infoX + 62, y);
|
||||||
|
if (c.breed) {
|
||||||
|
ctx.fillStyle = '#9A8F82';
|
||||||
|
ctx.font = '24px sans-serif';
|
||||||
|
ctx.fillText('品种', infoX + 62 + gw + 24, y);
|
||||||
|
ctx.fillStyle = '#2D2925';
|
||||||
|
ctx.font = '600 26px sans-serif';
|
||||||
|
ctx.fillText(c.breed, infoX + 62 + gw + 24 + 62, y);
|
||||||
|
}
|
||||||
|
y += 46;
|
||||||
|
line('出生', c.birthday);
|
||||||
|
line('介绍', c.intro);
|
||||||
|
|
||||||
|
// 身份 ID:虚线 + 号
|
||||||
|
const idY = pad + 300;
|
||||||
|
ctx.strokeStyle = 'rgba(122,74,8,.22)';
|
||||||
|
ctx.lineWidth = 1;
|
||||||
|
ctx.setLineDash([6, 6]);
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(pad + 34, idY);
|
||||||
|
ctx.lineTo(W - pad - 34, idY);
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.setLineDash([]);
|
||||||
|
ctx.textAlign = 'left';
|
||||||
|
ctx.font = '22px sans-serif';
|
||||||
|
ctx.fillStyle = '#9A8F82';
|
||||||
|
ctx.fillText('身份 ID', pad + 34, idY + 34);
|
||||||
|
ctx.font = '600 26px sans-serif';
|
||||||
|
ctx.fillStyle = '#2D2925';
|
||||||
|
ctx.fillText(c.id_no || '', pad + 34 + 90, idY + 34);
|
||||||
|
|
||||||
|
// ── 下半张:证件标题 + 小程序码 ──
|
||||||
|
const botY = topH + 12;
|
||||||
|
const botH = H - botY - pad;
|
||||||
|
const g2 = ctx.createLinearGradient(pad, botY, W - pad, botY + botH);
|
||||||
|
g2.addColorStop(0, '#E8F0FF');
|
||||||
|
g2.addColorStop(1, '#F0E8FF');
|
||||||
|
this.roundRect(ctx, pad, botY, cardW, botH, 28);
|
||||||
|
ctx.fillStyle = g2;
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
ctx.textAlign = 'left';
|
||||||
|
ctx.fillStyle = '#7D89A8';
|
||||||
|
ctx.font = '22px sans-serif';
|
||||||
|
ctx.fillText('宠 星 人 地 球 移 民', pad + 40, botY + 60);
|
||||||
|
ctx.fillStyle = '#4A5878';
|
||||||
|
ctx.font = '700 52px sans-serif';
|
||||||
|
ctx.fillText('居民身份卡', pad + 40, botY + 128);
|
||||||
|
|
||||||
|
ctx.fillStyle = '#8A93A8';
|
||||||
|
ctx.font = '22px sans-serif';
|
||||||
|
ctx.fillText('签发机构 肉垫计划', pad + 40, botY + 180);
|
||||||
|
ctx.fillText('有效期限 ' + (c.validity || '永久有效'), pad + 40, botY + 214);
|
||||||
|
|
||||||
|
// 小程序码(未发布时 qr 为 null,画个占位框)
|
||||||
|
const qrD = 128, qrX = W - pad - 40 - qrD, qrY = botY + botH - 40 - qrD;
|
||||||
|
ctx.fillStyle = '#fff';
|
||||||
|
this.roundRect(ctx, qrX, qrY, qrD, qrD, 12);
|
||||||
|
ctx.fill();
|
||||||
|
if (qr) {
|
||||||
|
ctx.drawImage(qr, qrX + 8, qrY + 8, qrD - 16, qrD - 16);
|
||||||
|
} else {
|
||||||
|
ctx.fillStyle = '#B5A99D';
|
||||||
|
ctx.font = '20px sans-serif';
|
||||||
|
ctx.textAlign = 'center';
|
||||||
|
ctx.fillText('小程序码', qrX + qrD / 2, qrY + qrD / 2 - 4);
|
||||||
|
ctx.fillText('待发布', qrX + qrD / 2, qrY + qrD / 2 + 26);
|
||||||
|
}
|
||||||
|
|
||||||
|
wx.canvasToTempFilePath(
|
||||||
|
{
|
||||||
|
canvas: node,
|
||||||
|
fileType: 'png',
|
||||||
|
success: (r) => this.setData({ cardImg: r.tempFilePath }),
|
||||||
|
fail: () => wx.showToast({ title: '生成失败,稍后再试', icon: 'none' }),
|
||||||
|
},
|
||||||
|
this,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
roundRect(ctx, x, y, w, h, r) {
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(x + r, y);
|
||||||
|
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||||
|
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||||
|
ctx.arcTo(x, y + h, x, y, r);
|
||||||
|
ctx.arcTo(x, y, x + w, y, r);
|
||||||
|
ctx.closePath();
|
||||||
|
},
|
||||||
|
|
||||||
|
onSave() {
|
||||||
|
if (!this.data.cardImg) return wx.showToast({ title: '还在生成,稍等一下', icon: 'none' });
|
||||||
|
if (this.data.saving) return;
|
||||||
|
this.setData({ saving: true });
|
||||||
|
wx.saveImageToPhotosAlbum({
|
||||||
|
filePath: this.data.cardImg,
|
||||||
|
success: () => wx.showToast({ title: '已保存到相册', icon: 'success' }),
|
||||||
|
fail: (err) => {
|
||||||
|
const msg = (err && err.errMsg) || '';
|
||||||
|
if (msg.indexOf('cancel') >= 0) return;
|
||||||
|
// 拒过一次后 authorize 不再弹,必须引导去设置页
|
||||||
|
if (msg.indexOf('auth deny') >= 0 || msg.indexOf('authorize') >= 0) {
|
||||||
|
wx.showModal({
|
||||||
|
title: '需要相册权限',
|
||||||
|
content: '保存身份卡需要允许访问相册,去设置里打开一下?',
|
||||||
|
confirmText: '去设置',
|
||||||
|
success: (r) => r.confirm && wx.openSetting({}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
wx.showToast({ title: '保存失败', icon: 'none' });
|
||||||
|
},
|
||||||
|
complete: () => this.setData({ saving: false }),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
onShareAppMessage() {
|
||||||
|
const c = this.data.card || {};
|
||||||
|
return {
|
||||||
|
title: `${c.name || '我家毛孩子'} 的居民身份卡`,
|
||||||
|
path: '/pages/idcard/idcard?id=' + this.data.petId,
|
||||||
|
imageUrl: this.data.cardImg || '', // 用画好的卡当分享封面
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"usingComponents": {
|
||||||
|
"nav-bar": "/components/nav-bar/nav-bar",
|
||||||
|
"pt-icon": "/components/pt-icon/index"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<nav-bar title="身份卡" show-back="{{true}}"></nav-bar>
|
||||||
|
|
||||||
|
<scroll-view class="page-scroll" scroll-y="{{true}}" enhanced="{{true}}" show-scrollbar="{{false}}">
|
||||||
|
<view class="page-body ic-body">
|
||||||
|
<!-- 画好的卡当成图片展示。canvas 本身是离屏的(挪到屏幕外),只用来生成图 -->
|
||||||
|
<view class="ic-stage">
|
||||||
|
<image wx:if="{{cardImg}}" class="ic-img" src="{{cardImg}}" mode="widthFix" show-menu-by-longpress="{{true}}"></image>
|
||||||
|
<view wx:else class="ic-loading">正在生成身份卡…</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view wx:if="{{!qrReady}}" class="ic-tip">
|
||||||
|
小程序码要在小程序发布后才会出现,现在先放一个占位。
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<view class="ic-actions">
|
||||||
|
<view class="btn btn-soft ic-btn" bindtap="onSave">
|
||||||
|
<pt-icon name="photo" size="{{32}}"></pt-icon>下载到相册
|
||||||
|
</view>
|
||||||
|
<button class="btn btn-dark ic-btn" open-type="share">
|
||||||
|
<pt-icon name="share" size="{{32}}"></pt-icon>分享给好友
|
||||||
|
</button>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
|
||||||
|
<!-- 离屏 canvas:挪到屏幕外,只用来画图导出 -->
|
||||||
|
<canvas type="2d" id="idCanvas" class="ic-canvas"></canvas>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
.ic-body{padding-top:var(--sp-4)}
|
||||||
|
|
||||||
|
/* 画好的卡片图。宽度撑满、按比例高 */
|
||||||
|
.ic-stage{border-radius:var(--r-lg);overflow:hidden;box-shadow:var(--sd-2);background:#F3EFE8;min-height:600rpx}
|
||||||
|
.ic-img{width:100%;display:block}
|
||||||
|
.ic-loading{padding:200rpx 0;text-align:center;color:var(--muted);font-size:var(--fs-sm)}
|
||||||
|
|
||||||
|
.ic-tip{
|
||||||
|
margin-top:var(--sp-4);padding:var(--sp-3);border-radius:var(--r-sm);
|
||||||
|
background:var(--primary-soft);color:var(--primary-ink);
|
||||||
|
font-size:var(--fs-cap);line-height:1.6;text-align:center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ic-actions{display:flex;gap:var(--sp-3);margin-top:var(--sp-5)}
|
||||||
|
.ic-btn{flex:1}
|
||||||
|
/* button 元素默认有边框和外边距,压平成和 .btn 一样 */
|
||||||
|
button.ic-btn{padding:0;line-height:normal}
|
||||||
|
button.ic-btn::after{border:none}
|
||||||
|
|
||||||
|
/* 离屏 canvas:挪出可视区,只用来生成图 */
|
||||||
|
.ic-canvas{position:fixed;left:-9999rpx;top:0;width:620px;height:760px}
|
||||||
@@ -56,6 +56,12 @@ Page({
|
|||||||
goDecorate() {
|
goDecorate() {
|
||||||
wx.navigateTo({ url: '/pages/decorate/decorate' });
|
wx.navigateTo({ url: '/pages/decorate/decorate' });
|
||||||
},
|
},
|
||||||
|
// 身份卡:当前这只的
|
||||||
|
goIDCard() {
|
||||||
|
const id = store.currentPetId();
|
||||||
|
if (!id) return wx.showToast({ title: '先选一只毛孩子', icon: 'none' });
|
||||||
|
wx.navigateTo({ url: '/pages/idcard/idcard?id=' + id });
|
||||||
|
},
|
||||||
goPlan() {
|
goPlan() {
|
||||||
wx.navigateTo({ url: '/pages/plan/plan' });
|
wx.navigateTo({ url: '/pages/plan/plan' });
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -33,6 +33,10 @@
|
|||||||
<view class="pr-ic"><pt-icon name="user" size="{{34}}"></pt-icon></view>
|
<view class="pr-ic"><pt-icon name="user" size="{{34}}"></pt-icon></view>
|
||||||
<text class="pr-label">宠物档案</text><view class="pr-arrow"><pt-icon name="next" size="{{28}}"></pt-icon></view>
|
<text class="pr-label">宠物档案</text><view class="pr-arrow"><pt-icon name="next" size="{{28}}"></pt-icon></view>
|
||||||
</view>
|
</view>
|
||||||
|
<view class="profile-row" bindtap="goIDCard">
|
||||||
|
<view class="pr-ic"><pt-icon name="user" size="{{34}}"></pt-icon></view>
|
||||||
|
<text class="pr-label">身份卡</text><text class="pr-val">可保存、分享</text><view class="pr-arrow"><pt-icon name="next" size="{{28}}"></pt-icon></view>
|
||||||
|
</view>
|
||||||
<view class="profile-row" bindtap="goPlan">
|
<view class="profile-row" bindtap="goPlan">
|
||||||
<view class="pr-ic"><pt-icon name="plan" size="{{34}}"></pt-icon></view>
|
<view class="pr-ic"><pt-icon name="plan" size="{{34}}"></pt-icon></view>
|
||||||
<text class="pr-label">养护计划</text><view class="pr-arrow"><pt-icon name="next" size="{{28}}"></pt-icon></view>
|
<text class="pr-label">养护计划</text><view class="pr-arrow"><pt-icon name="next" size="{{28}}"></pt-icon></view>
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ const api = {
|
|||||||
// 否则改了阈值忘了改文案,用户看到的依据和实际行为对不上
|
// 否则改了阈值忘了改文案,用户看到的依据和实际行为对不上
|
||||||
lifeStages: (species, size) =>
|
lifeStages: (species, size) =>
|
||||||
request({ url: `/api/life-stages?species=${species}&size=${size || ''}` }),
|
request({ url: `/api/life-stages?species=${species}&size=${size || ''}` }),
|
||||||
|
petIDCard: (id) => request({ url: `/api/pets/${id}/id-card` }),
|
||||||
petStageDrift: (petId) => request({ url: `/api/pets/${petId}/stage-drift` }),
|
petStageDrift: (petId) => request({ url: `/api/pets/${petId}/stage-drift` }),
|
||||||
|
|
||||||
// 品种(后台可配),按首字母分组
|
// 品种(后台可配),按首字母分组
|
||||||
|
|||||||
Reference in New Issue
Block a user