feat: 汉字每天打卡基本完成,细节还待优化
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
import { GRID_COLORS } from '../../core/data/tracingStyles';
|
||||
|
||||
/**
|
||||
* cnchar-data 1024×1024 坐标系
|
||||
*/
|
||||
export const CHAR_BOUNDS = {
|
||||
minX: 0,
|
||||
minY: -124,
|
||||
maxX: 1024,
|
||||
maxY: 900,
|
||||
};
|
||||
export const CHAR_WIDTH = CHAR_BOUNDS.maxX - CHAR_BOUNDS.minX;
|
||||
export const CHAR_HEIGHT = CHAR_BOUNDS.maxY - CHAR_BOUNDS.minY;
|
||||
|
||||
export interface ScalingTransform {
|
||||
xOffset: number;
|
||||
yOffset: number;
|
||||
scale: number;
|
||||
}
|
||||
|
||||
export function getScalingTransform(
|
||||
width: number,
|
||||
height: number,
|
||||
padding: number,
|
||||
): ScalingTransform {
|
||||
const availableWidth = width - 2 * padding;
|
||||
const availableHeight = height - 2 * padding;
|
||||
|
||||
const scaleX = availableWidth / CHAR_WIDTH;
|
||||
const scaleY = availableHeight / CHAR_HEIGHT;
|
||||
const scale = Math.min(scaleX, scaleY);
|
||||
|
||||
const scaledWidth = CHAR_WIDTH * scale;
|
||||
const scaledHeight = CHAR_HEIGHT * scale;
|
||||
const centerX = padding + (availableWidth - scaledWidth) / 2;
|
||||
const centerY = padding + (availableHeight - scaledHeight) / 2;
|
||||
|
||||
const xOffset = -CHAR_BOUNDS.minX * scale + centerX;
|
||||
const yOffset = -CHAR_BOUNDS.minY * scale + centerY;
|
||||
|
||||
return { xOffset, yOffset, scale };
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG 路径解析与绘制(支持 M/L/Q/Z 命令)
|
||||
*/
|
||||
export function drawSvgPath(ctx: RenderingContext, pathD: string) {
|
||||
const commandRegex = /([MLQZ])([^MLQZ]*?)(?=[MLQZ]|$)/gi;
|
||||
const commands: Array<{ cmd: string; coords: string }> = [];
|
||||
let match;
|
||||
while ((match = commandRegex.exec(pathD)) !== null) {
|
||||
commands.push({ cmd: match[1].toUpperCase(), coords: match[2].trim() });
|
||||
}
|
||||
const parseCoords = (coords: string): number[] =>
|
||||
coords
|
||||
.split(/[\s,]+/)
|
||||
.filter((part) => part.trim() !== '')
|
||||
.map((part) => parseFloat(part));
|
||||
|
||||
for (const { cmd, coords } of commands) {
|
||||
const v = parseCoords(coords);
|
||||
switch (cmd) {
|
||||
case 'M':
|
||||
if (v.length >= 2) ctx.moveTo(v[0], v[1]);
|
||||
break;
|
||||
case 'L':
|
||||
if (v.length >= 2) ctx.lineTo(v[0], v[1]);
|
||||
break;
|
||||
case 'Q':
|
||||
if (v.length >= 4) ctx.quadraticCurveTo(v[0], v[1], v[2], v[3]);
|
||||
break;
|
||||
case 'Z':
|
||||
ctx.closePath();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const GRID_CROSS_DASH = [4, 3];
|
||||
|
||||
export interface DrawTianZiGridParams {
|
||||
ctx: RenderingContext;
|
||||
/** 田字格中心 x */
|
||||
cx: number;
|
||||
/** 田字格中心 y */
|
||||
cy: number;
|
||||
/** 田字格边长 */
|
||||
size: number;
|
||||
borderColor?: string;
|
||||
middleLineColor?: string;
|
||||
diagonalColor?: string;
|
||||
/** 是否绘制对角线(X线),默认不绘制 */
|
||||
showDiagonal?: boolean;
|
||||
}
|
||||
|
||||
export function drawTianZiGrid({
|
||||
ctx,
|
||||
cx,
|
||||
cy,
|
||||
size,
|
||||
borderColor = GRID_COLORS.border,
|
||||
middleLineColor = GRID_COLORS.middleLine,
|
||||
diagonalColor = GRID_COLORS.diagonal,
|
||||
showDiagonal = false,
|
||||
}: DrawTianZiGridParams) {
|
||||
const half = size / 2;
|
||||
|
||||
// 外边框 — 实线
|
||||
ctx.strokeStyle = borderColor;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.setLineDash([]);
|
||||
ctx.strokeRect(cx - half, cy - half, size, size);
|
||||
|
||||
// 十字线 — 虚线
|
||||
ctx.strokeStyle = middleLineColor;
|
||||
ctx.setLineDash(GRID_CROSS_DASH);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cx, cy - half);
|
||||
ctx.lineTo(cx, cy + half);
|
||||
ctx.moveTo(cx - half, cy);
|
||||
ctx.lineTo(cx + half, cy);
|
||||
ctx.stroke();
|
||||
|
||||
// 对角线 — 虚线
|
||||
if (showDiagonal) {
|
||||
ctx.strokeStyle = diagonalColor;
|
||||
ctx.setLineDash(GRID_CROSS_DASH);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cx - half, cy - half);
|
||||
ctx.lineTo(cx + half, cy + half);
|
||||
ctx.moveTo(cx + half, cy - half);
|
||||
ctx.lineTo(cx - half, cy + half);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { getJson } from '../../utils/http';
|
||||
|
||||
/**
|
||||
* SVG汉字数据缓存配置
|
||||
*/
|
||||
const CACHE_CONFIG = {
|
||||
key: 'svgWordsData', // 缓存键名
|
||||
expireDays: 7, // 缓存过期天数
|
||||
// url: 'https://cdn.joeyone.cn/doodle/words-svg-all.json' // 远程数据地址
|
||||
// url: 'https://cdn.joeyone.cn/doodle/words-svg-3000.json' // 远程数据地址
|
||||
// url: 'https://cdn.joeyone.cn/doodle/char_svg_3500.json' // 远程数据地址
|
||||
url: 'https://cdn.joeyone.cn/doodle/hanzi/hanzi_stroke_3500.json', // 远程数据地址
|
||||
hanziReadingsUrl:
|
||||
'https://cdn.joeyone.cn/doodle/hanzi/hanzi_readings_3500.json', // 远程数据地址
|
||||
};
|
||||
|
||||
/**
|
||||
* 汉字读音数据缓存配置
|
||||
*/
|
||||
const READINGS_CACHE_CONFIG = {
|
||||
key: 'hanziReadingsData',
|
||||
expireDays: 7,
|
||||
url: CACHE_CONFIG.hanziReadingsUrl,
|
||||
};
|
||||
|
||||
/**
|
||||
* 汉字读音原始数据条目:
|
||||
* - 单音字:[pinyin, gloss, introduce]
|
||||
* - 多音字:[[pinyin, gloss, introduce], ...]
|
||||
*/
|
||||
export type HanziReadingEntry =
|
||||
| [string, string, string]
|
||||
| [string, string, string][];
|
||||
export type HanziReadingsMap = Record<string, HanziReadingEntry>;
|
||||
|
||||
/**
|
||||
* 缓存数据结构
|
||||
*/
|
||||
interface CacheData {
|
||||
data: Record<string, string[]>; // SVG汉字数据
|
||||
timestamp: number; // 缓存时间戳
|
||||
version?: string; // 数据版本(可选)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查缓存是否过期
|
||||
* @param timestamp 缓存时间戳
|
||||
* @returns 是否过期
|
||||
*/
|
||||
function isCacheExpired(timestamp: number): boolean {
|
||||
const now = Date.now();
|
||||
const expireTime = CACHE_CONFIG.expireDays * 24 * 60 * 60 * 1000; // 7天的毫秒数
|
||||
return now - timestamp > expireTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从本地存储获取缓存数据
|
||||
* @returns 缓存数据或null
|
||||
*/
|
||||
function getCacheData(): CacheData | null {
|
||||
try {
|
||||
const cacheStr = wx.getStorageSync(CACHE_CONFIG.key);
|
||||
if (!cacheStr) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheData: CacheData = JSON.parse(cacheStr);
|
||||
|
||||
// 检查缓存是否过期
|
||||
if (isCacheExpired(cacheData.timestamp)) {
|
||||
console.log('SVG汉字数据缓存已过期,将重新获取');
|
||||
// 清除过期缓存
|
||||
wx.removeStorageSync(CACHE_CONFIG.key);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log(
|
||||
'使用本地缓存的SVG汉字数据,缓存时间:',
|
||||
new Date(cacheData.timestamp).toLocaleString(),
|
||||
);
|
||||
return cacheData;
|
||||
} catch (error) {
|
||||
console.error('读取SVG汉字数据缓存失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存数据到本地存储
|
||||
* @param data SVG汉字数据
|
||||
*/
|
||||
function saveCacheData(data: Record<string, string[]>): void {
|
||||
try {
|
||||
const cacheData: CacheData = {
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
version: '1.0', // 可以用于后续版本控制
|
||||
};
|
||||
|
||||
wx.setStorageSync(CACHE_CONFIG.key, JSON.stringify(cacheData));
|
||||
console.log('SVG汉字数据已缓存到本地存储');
|
||||
} catch (error) {
|
||||
console.error('保存SVG汉字数据缓存失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从远程服务器获取SVG汉字数据
|
||||
* @returns Promise<Record<string, string[]>>
|
||||
*/
|
||||
async function fetchRemoteData(): Promise<Record<string, string[]>> {
|
||||
console.log('从远程服务器获取SVG汉字数据...');
|
||||
|
||||
const svgWordsData = await getJson<Record<string, string[]>>(
|
||||
CACHE_CONFIG.url,
|
||||
{
|
||||
timeout: 15000, // 15秒超时
|
||||
header: {
|
||||
Accept: 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
console.log(
|
||||
'远程SVG汉字数据获取成功,共',
|
||||
Object.keys(svgWordsData).length,
|
||||
'个汉字',
|
||||
);
|
||||
return svgWordsData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取SVG汉字数据(带缓存机制)
|
||||
* 优先使用本地缓存,如果缓存不存在或已过期,则从远程获取
|
||||
* @returns Promise<Record<string, string[]>>
|
||||
*/
|
||||
export async function getWordsSvgData(): Promise<Record<string, string[]>> {
|
||||
try {
|
||||
// 1. 尝试从本地缓存获取数据
|
||||
const cacheData = getCacheData();
|
||||
if (cacheData) {
|
||||
return cacheData.data;
|
||||
}
|
||||
|
||||
// 2. 缓存不存在或已过期,从远程获取
|
||||
const remoteData = await fetchRemoteData();
|
||||
|
||||
// 3. 保存到本地缓存
|
||||
saveCacheData(remoteData);
|
||||
|
||||
return remoteData;
|
||||
} catch (error) {
|
||||
console.error('获取SVG汉字数据失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取汉字读音数据(带缓存机制)
|
||||
* 数据格式参见 HanziReadingsMap 类型说明,单音字为一维数组,多音字为二维数组。
|
||||
*/
|
||||
export async function getHanziReadingsData(): Promise<HanziReadingsMap> {
|
||||
try {
|
||||
const cacheStr = wx.getStorageSync(READINGS_CACHE_CONFIG.key);
|
||||
if (cacheStr) {
|
||||
const cacheData = JSON.parse(cacheStr) as {
|
||||
data: HanziReadingsMap;
|
||||
timestamp: number;
|
||||
};
|
||||
const expireMs =
|
||||
READINGS_CACHE_CONFIG.expireDays * 24 * 60 * 60 * 1000;
|
||||
if (Date.now() - cacheData.timestamp <= expireMs) {
|
||||
return cacheData.data;
|
||||
}
|
||||
wx.removeStorageSync(READINGS_CACHE_CONFIG.key);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('读取汉字读音缓存失败:', error);
|
||||
}
|
||||
|
||||
const remote = await getJson<HanziReadingsMap>(READINGS_CACHE_CONFIG.url, {
|
||||
timeout: 15000,
|
||||
header: {
|
||||
Accept: 'application/json',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
wx.setStorageSync(
|
||||
READINGS_CACHE_CONFIG.key,
|
||||
JSON.stringify({ data: remote, timestamp: Date.now() }),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('保存汉字读音缓存失败:', error);
|
||||
}
|
||||
|
||||
return remote;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出汉字的主拼音(多音字取第一个发音),未命中或数据非法时返回空串。
|
||||
*/
|
||||
export function pickPrimaryPinyin(
|
||||
readings: HanziReadingsMap,
|
||||
char: string,
|
||||
): string {
|
||||
const entry = readings[char];
|
||||
if (!entry) return '';
|
||||
if (typeof entry[0] === 'string') {
|
||||
return (entry as [string, string, string])[0] || '';
|
||||
}
|
||||
const first = (entry as [string, string, string][])[0];
|
||||
return Array.isArray(first) ? first[0] || '' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除SVG汉字数据缓存
|
||||
*/
|
||||
export function clearWordsSvgCache(): void {
|
||||
try {
|
||||
wx.removeStorageSync(CACHE_CONFIG.key);
|
||||
console.log('SVG汉字数据缓存已清除');
|
||||
} catch (error) {
|
||||
console.error('清除SVG汉字数据缓存失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存信息
|
||||
* @returns 缓存信息对象
|
||||
*/
|
||||
export function getCacheInfo(): {
|
||||
exists: boolean;
|
||||
timestamp?: number;
|
||||
isExpired?: boolean;
|
||||
daysLeft?: number;
|
||||
} {
|
||||
try {
|
||||
const cacheStr = wx.getStorageSync(CACHE_CONFIG.key);
|
||||
if (!cacheStr) {
|
||||
return { exists: false };
|
||||
}
|
||||
|
||||
const cacheData: CacheData = JSON.parse(cacheStr);
|
||||
const isExpired = isCacheExpired(cacheData.timestamp);
|
||||
const daysLeft = isExpired
|
||||
? 0
|
||||
: Math.ceil(
|
||||
(CACHE_CONFIG.expireDays * 24 * 60 * 60 * 1000 -
|
||||
(Date.now() - cacheData.timestamp)) /
|
||||
(24 * 60 * 60 * 1000),
|
||||
);
|
||||
|
||||
return {
|
||||
exists: true,
|
||||
timestamp: cacheData.timestamp,
|
||||
isExpired,
|
||||
daysLeft,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取缓存信息失败:', error);
|
||||
return { exists: false };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user