feat: 完成绘制汉字基础功能

This commit is contained in:
R524809
2025-10-17 17:48:34 +08:00
parent 7ac81eb961
commit 2734b9de9e
18 changed files with 16428 additions and 299 deletions
+468 -150
View File
@@ -1,82 +1,159 @@
import { PAPER_SIZE } from '../constants/colors';
import { getMiniCodeImage, getImage } from '../utils/index';
/**
* 仅支持 M/L/Z 的简单 SVG 路径解析与绘制
*/
function drawSvgPathCommands(
ctx: RenderingContext,
pathD: string,
offsetX: number,
offsetY: number,
scale: number,
) {
const tokens = pathD
.replace(/,/g, ' ')
.trim()
.split(/\s+/);
let i = 0;
let currentX = 0;
let currentY = 0;
while (i < tokens.length) {
const cmd = tokens[i++];
switch (cmd) {
case 'M': {
const x = parseFloat(tokens[i++]);
const y = parseFloat(tokens[i++]);
currentX = offsetX + x * scale;
currentY = offsetY + y * scale;
ctx.moveTo(currentX, currentY);
break;
}
case 'L': {
const x = parseFloat(tokens[i++]);
const y = parseFloat(tokens[i++]);
currentX = offsetX + x * scale;
currentY = offsetY + y * scale;
ctx.lineTo(currentX, currentY);
break;
}
case 'Z': {
ctx.closePath();
break;
}
default: {
// 遇到数字(可能因为路径省略了连续的 L),回退一步并按 L 处理
if (!isNaN(parseFloat(cmd))) {
i--;
const x = parseFloat(tokens[i++]);
const y = parseFloat(tokens[i++]);
currentX = offsetX + x * scale;
currentY = offsetY + y * scale;
ctx.lineTo(currentX, currentY);
break;
}
// 其他命令不支持,直接跳过
break;
}
}
}
interface DrawSvgPathCommandsParams {
ctx: RenderingContext;
pathD: string;
offsetX: number;
offsetY: number;
scale: number;
}
function drawStrokes(
ctx: RenderingContext,
strokes: string[],
offsetX: number,
offsetY: number,
size: number,
uptoInclusive: number,
fillStyle: string,
strokeStyle: string,
lineWidth: number,
) {
function drawSvgPathCommands({
ctx,
pathD,
offsetX,
offsetY,
scale
}: DrawSvgPathCommandsParams) {
// console.log('drawSvgPathCommands 参数:', { pathD, offsetX, offsetY, scale });
// 精度处理函数:避免浮点数精度问题
const roundToPrecision = (num: number, precision: number = 2): number => {
return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
};
// 新的解析方法:按命令片段解析
// 使用正则表达式匹配从字母开头到下一个字母(或结尾)的片段
const commandRegex = /([MLZ])([^MLZ]*?)(?=[MLZ]|$)/g;
const commands: Array<{ cmd: string, coords: string }> = [];
let match;
while ((match = commandRegex.exec(pathD)) !== null) {
const cmd = match[1];
const coords = match[2].trim();
commands.push({ cmd, coords });
}
// console.log('解析的命令片段:', commands);
let commandCount = 0;
// 优化的坐标解析和绘制函数
const parseAndDrawCoords = (coords: string, cmd: string, drawFunction: (x: number, y: number) => void) => {
// 更严格的坐标解析:支持负数和小数
const coordParts = coords.split(/\s+/).filter(part => part.trim() !== '');
if (coordParts.length >= 2) {
const x = parseFloat(coordParts[0]);
const y = parseFloat(coordParts[1]);
if (!isNaN(x) && !isNaN(y) && isFinite(x) && isFinite(y)) {
// 计算最终坐标并处理精度
const finalX = roundToPrecision(offsetX + x * scale);
const finalY = roundToPrecision(offsetY + y * scale);
// console.log(`${cmd}: 绘制到 (${finalX}, ${finalY}) [原始: (${x}, ${y})]`);
drawFunction(finalX, finalY);
} else {
console.warn(`${cmd}: 坐标解析失败 - x=${x}, y=${y}, 原始坐标: "${coords}"`);
}
} else {
console.warn(`${cmd}: 坐标数量不足,需要2个,实际${coordParts.length}个,原始: "${coords}"`);
}
};
// 命令处理映射表,提高可读性和可扩展性
const commandHandlers: Record<string, (coords: string) => void> = {
'M': (coords) => parseAndDrawCoords(coords, 'M', (x, y) => ctx.moveTo(x, y)),
'L': (coords) => parseAndDrawCoords(coords, 'L', (x, y) => ctx.lineTo(x, y)),
'Z': () => {
// console.log('Z: 闭合路径');
// 注意:不要在这里调用 closePath(),因为 drawStrokes 中会统一处理
}
};
for (const { cmd, coords } of commands) {
commandCount++;
// console.log(`命令 ${commandCount}: ${cmd}, 坐标: "${coords}"`);
const handler = commandHandlers[cmd];
if (handler) {
handler(coords);
} else {
console.warn(`未知命令: ${cmd}`);
}
}
// console.log(`总共处理了 ${commandCount} 个命令`);
}
interface DrawStrokesParams {
ctx: RenderingContext;
strokes: string[];
offsetX: number;
offsetY: number;
size: number;
uptoInclusive: number;
fillStyle: string;
strokeStyle: string;
lineWidth: number;
}
function drawStrokes({
ctx,
strokes,
offsetX,
offsetY,
size,
uptoInclusive,
fillStyle,
strokeStyle,
lineWidth
}: DrawStrokesParams) {
// 模板中使用 54x54 的视窗尺寸
const viewBoxSize = 54;
const scale = size / viewBoxSize;
// 添加内边距:在田字格四周预留空间,避免笔画贴边
const padding = size * 0.1; // 内边距为田字格大小的10%
const contentSize = size - padding * 2; // 实际绘制区域大小
const contentScale = contentSize / viewBoxSize; // 调整后的缩放比例
// 计算内容区域的起始位置(居中)
const contentOffsetX = offsetX + padding;
const contentOffsetY = offsetY + padding;
console.log('drawStrokes 参数:', {
strokesCount: strokes.length,
uptoInclusive,
offsetX,
offsetY,
size,
padding,
contentSize,
contentOffsetX,
contentOffsetY,
originalScale: scale,
contentScale,
fillStyle,
strokeStyle,
lineWidth
});
for (let s = 0; s <= uptoInclusive && s < strokes.length; s++) {
// console.log(`绘制第 ${s} 个笔画:`, strokes[s]);
ctx.beginPath();
drawSvgPathCommands(ctx, strokes[s], offsetX, offsetY, scale);
drawSvgPathCommands({
ctx,
pathD: strokes[s],
offsetX: contentOffsetX,
offsetY: contentOffsetY,
scale: contentScale
});
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
@@ -86,14 +163,23 @@ function drawStrokes(
}
}
function drawTianZiGrid(
ctx: RenderingContext,
x: number,
y: number,
size: number,
lineColor: string = '#e0e0e0',
boldColor: string = '#cccccc',
) {
interface DrawTianZiGridParams {
ctx: RenderingContext;
x: number;
y: number;
size: number;
lineColor?: string;
boldColor?: string;
}
function drawTianZiGrid({
ctx,
x,
y,
size,
lineColor = '#e0e0e0',
boldColor = '#cccccc'
}: DrawTianZiGridParams) {
// 外框
ctx.strokeStyle = boldColor;
ctx.lineWidth = 2;
@@ -144,7 +230,7 @@ class WordDrawService {
this.paperSize = 'A4';
this.options = {
appName: '涂鸦丫小程序',
appHint: '字|识字|打印',
appHint: '字|识图|练字|打印',
title: '田字格 练 字 贴',
subTitle: '按笔画临摹练习',
...options,
@@ -164,15 +250,19 @@ class WordDrawService {
* 生成练字帖
* @param wordsMap 形如 { "其": ["M.. L.. Z", ...], ... },不超过 10 个汉字
*/
draw(wordsMap: Record<string, string[]>) {
async draw(wordsMap: Record<string, string[]>) {
this.setPrintConfig();
this.clear();
this.setPaper();
// 等待页眉绘制完成,确保 this.currentY 被正确设置
if (this.headerType !== 'minimal') {
this.drawHeader();
await this.drawHeader();
} else {
this.drawMiniHeader();
await this.drawMiniHeader();
}
// 页眉绘制完成后,再绘制内容
this.drawContent(wordsMap);
}
@@ -190,13 +280,25 @@ class WordDrawService {
const logoWidth = 200;
const logoHeight = 200;
// 这里沿用小程序码/Logo策略,保持与其它服务一致
try {
const { getMiniCodeImage } = await import('../utils/index');
const image = await getMiniCodeImage(canvas);
ctx.drawImage(image, logoX, logoY, logoWidth, logoHeight);
} catch (_) {
// 忽略加载失败
switch (this.headerType) {
case 'LogoImage': {
const image = await getImage(canvas, '/assets/imgs/doodle-logo.png');
ctx.drawImage(image, logoX, logoY, logoWidth, logoHeight);
break;
}
case 'noLogoImage': {
titleX = 120;
break;
}
case 'minimal': {
titleX = 120;
break;
}
default: {
const image = await getMiniCodeImage(canvas);
ctx.drawImage(image, logoX, logoY, logoWidth, logoHeight);
break;
}
}
ctx.font = 'bold 64px "Microsoft Yahei"';
@@ -217,7 +319,10 @@ class WordDrawService {
ctx.fillStyle = '#666';
ctx.fillText(subTitle, 1015, 186);
this.currentY = 304;
// 计算页眉的实际高度,包括分割线
const headerHeight = Math.max(logoY + logoHeight, titleY + 64 + 48 + 48) + 20; // 64px字体 + 48px间距 + 48px字体 + 20px边距
// this.currentY = headerHeight;
this.currentY += headerHeight;
this.drawLine(this.currentY);
}
@@ -230,12 +335,24 @@ class WordDrawService {
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.fillText(appName + ' ' + title, canvas.width / 2, titleY);
this.currentY = 200;
// 计算迷你页眉的实际高度
const miniHeaderHeight = titleY + 64 + 20; // 64px字体 + 20px边距
this.currentY = miniHeaderHeight;
this.drawLine(this.currentY);
}
/**
* 绘制正文内容:为每个汉字生成“预览 + 逐笔画临摹 + 空白格”的练习单元
* 绘制正文内容:两阶段绘制 - 先绘制空田字格,再绘制练字内容
*/
/**
* 绘制正文内容:包括田字格的排布和内容
*
* minGap 作用解释:
* minGap(最小列间距)用于田字格水平方向(每一行格子之间的间距)的初始最小值。它保证多个田字格在一行内不会紧贴排布、而是有一个最小的间隔,整体看起来不会拥挤。后续还会结合画布实际剩余空间动态调整为更合适的实际间距 actualColGap。
*
* rowGap 作用解释:
* rowGap(行间距)用于田字格竖直方向(每一行田字格之间的间隔)的初始最小值。它防止行与行的田字格上下贴得太紧,增加一定的可视呼吸空间。之后同样会结合剩余空间动态调整为实际间距 actualRowGap。
*/
drawContent(wordsMap: Record<string, string[]>) {
const { canvas, ctx } = this;
@@ -248,84 +365,285 @@ class WordDrawService {
const rightMargin = 120;
const bottomMargin = 120;
const contentTop = this.currentY + topGap;
console.log('contentTop----:', contentTop)
const contentWidth = canvas.width - leftMargin - rightMargin;
const contentHeight = canvas.height - contentTop - bottomMargin;
const cellSize = 140;
const minGap = 24;
const minGap = 24; // 最小格子列间距,用于保证横向不拥挤,后续可动态调整为实际间距
const rowGap = 36; // 最小格子行间距,用于保证纵向不拥挤,后续可动态调整为实际间距
// 计算每行可容纳的田字格数量
const maxPerRow = Math.max(1, Math.floor((contentWidth + minGap) / (cellSize + minGap)));
const rowGap = 36;
// 为每个汉字生成一串单元:1个预览 + N个逐笔画 + 2个空白 (便于描摹)
const unitsPerCharBuilder = (strokeCount: number) => {
const preview = 1;
const practice = Math.min(strokeCount, 8); // 最多展示 8 步逐笔画,避免过长
const blanks = 2;
return preview + practice + blanks;
};
// 计算每列可容纳的田字格数量
const actualRows = Math.max(1, Math.floor((contentHeight + rowGap) / (cellSize + rowGap)));
let cursorX = leftMargin;
let cursorY = contentTop + cellSize / 2;
let usedInRow = 0;
// 计算总需要的田字格数量
const totalCellsNeeded = actualRows * maxPerRow;
characters.forEach((char) => {
const strokes = wordsMap[char] || [];
const totalUnits = unitsPerCharBuilder(strokes.length);
let unitIndex = 0;
// 计算实际需要的行数
console.log('actualRows----:', actualRows)
console.log('totalCellsNeeded----:', totalCellsNeeded)
console.log('maxPerRow----:', maxPerRow)
while (unitIndex < totalUnits) {
// 如果本行放不下,换行
if (usedInRow >= maxPerRow) {
cursorX = leftMargin;
cursorY += cellSize + rowGap;
usedInRow = 0;
// 边界检查
if (cursorY + cellSize / 2 > canvas.height - bottomMargin) return;
}
// 动态调整间距以充分利用空间(在允许的最小间距基础上弹性扩展以适配画布)
const actualRowGap = actualRows > 1 ? (contentHeight - actualRows * cellSize) / (actualRows - 1) : 0;
const actualColGap = maxPerRow > 1 ? (contentWidth - maxPerRow * cellSize) / (maxPerRow - 1) : 0;
// 绘制田字格
drawTianZiGrid(ctx, cursorX + cellSize / 2, cursorY, cellSize);
console.log(`布局信息: 总格数=${totalCellsNeeded}, 行数=${actualRows}, 列数=${maxPerRow}, 行间距=${actualRowGap.toFixed(1)}, 列间距=${actualColGap.toFixed(1)}`);
// 单元类型:0 预览;1..practice 逐笔画;最后 blanks 空白
const practiceMax = Math.min(strokes.length, 8);
if (unitIndex === 0) {
// 预览:全部笔画使用较深颜色
drawStrokes(
ctx,
strokes,
cursorX + (cellSize - cellSize) / 2,
cursorY - cellSize / 2,
cellSize,
strokes.length - 1,
'rgb(0,0,0)',
'#000',
1.6,
);
} else if (unitIndex <= practiceMax) {
// 逐笔画:累进显示到第 k 画,使用灰色/描边
drawStrokes(
ctx,
strokes,
cursorX + (cellSize - cellSize) / 2,
cursorY - cellSize / 2,
cellSize,
unitIndex - 1,
'rgb(184,184,184)',
'#999',
1.6,
);
} else {
// 空白格:不画笔画
}
// 第一阶段:绘制所有空田字格
this.drawEmptyGrids({
ctx,
startX: leftMargin,
startY: contentTop,
cellSize,
colGap: actualColGap,
rowGap: actualRowGap,
maxPerRow,
maxRows: actualRows
});
// 前进到下一个单元
cursorX += cellSize + minGap;
usedInRow += 1;
unitIndex += 1;
// 第二阶段:绘制练字内容
this.drawPracticeContent({
ctx,
wordsMap,
startX: leftMargin,
startY: contentTop,
cellSize,
colGap: actualColGap,
rowGap: actualRowGap,
maxPerRow
});
}
/**
* 计算总需要的田字格数量
*/
// calculateTotalCellsNeeded(characters: string[], wordsMap: Record<string, string[]>): number {
// let totalCells = 0;
// characters.forEach((char) => {
// const strokes = wordsMap[char] || [];
// const strokeCount = strokes.length;
// const preview = 1; // 预览格
// const practice = Math.min(strokeCount, 8); // 最多8个练习格
// const blanks = 2; // 空白格
// totalCells += preview + practice + blanks;
// });
// return totalCells;
// }
/**
* 绘制空田字格网格
*/
drawEmptyGrids({
ctx,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow,
maxRows
}: {
ctx: RenderingContext;
startX: number;
startY: number;
cellSize: number;
colGap: number;
rowGap: number;
maxPerRow: number;
maxRows: number;
}) {
console.log('drawEmptyGrids startY----:', startY)
for (let row = 0; row < maxRows; row++) {
for (let col = 0; col < maxPerRow; col++) {
const x = startX + col * (cellSize + colGap) + cellSize / 2;
const y = startY + row * (cellSize + rowGap) + cellSize / 2;
drawTianZiGrid({ ctx, x, y, size: cellSize });
}
}
}
/**
* 绘制练字内容(参考 template.html 的实现)
*/
drawPracticeContent({
ctx,
wordsMap,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow
}: {
ctx: RenderingContext;
wordsMap: Record<string, string[]>;
startX: number;
startY: number;
cellSize: number;
colGap: number;
rowGap: number;
maxPerRow: number;
}) {
const characters = Object.keys(wordsMap);
let cellIndex = 0;
console.log('开始绘制练字内容,汉字数量:', characters.length);
characters.forEach((char, charIndex) => {
const strokes = wordsMap[char] || [];
const strokeCount = strokes.length;
console.log(`绘制第 ${charIndex + 1} 个汉字 "${char}",笔画数: ${strokeCount}`);
// 1. 预览格:显示完整汉字(黑色)
this.drawPreviewCell({
ctx,
strokes,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow,
cellIndex
});
cellIndex++;
// 2. 练习格:逐笔画显示(红色)
for (let strokeIndex = 0; strokeIndex < strokeCount; strokeIndex++) {
// 先绘制当前笔画
this.drawPracticeCell({
ctx,
strokes,
strokeIndex,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow,
cellIndex
});
cellIndex++;
console.log(`笔画 ${strokeIndex + 1} 绘制完成,当前 cellIndex: ${cellIndex}`);
}
// 3. 汉字间留空:每个汉字后留2个空白格
cellIndex += 0;
// 4. 强制下一个汉字换行到新行的第一个田字格
if (charIndex < characters.length - 1) { // 不是最后一个汉字
const currentRow = Math.floor(cellIndex / maxPerRow);
const nextRow = currentRow + 1;
cellIndex = nextRow * maxPerRow;
console.log(`汉字 "${char}" 绘制完成,强制换行到新行,下一个汉字从 cellIndex: ${cellIndex} 开始`);
} else {
console.log(`汉字 "${char}" 绘制完成,这是最后一个汉字`);
}
});
console.log('所有汉字绘制完成');
}
/**
* 绘制预览格(完整汉字)
*/
drawPreviewCell({
ctx,
strokes,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow,
cellIndex
}: {
ctx: RenderingContext;
strokes: string[];
startX: number;
startY: number;
cellSize: number;
colGap: number;
rowGap: number;
maxPerRow: number;
cellIndex: number;
}) {
const row = Math.floor(cellIndex / maxPerRow);
const col = cellIndex % maxPerRow;
const x = startX + col * (cellSize + colGap);
const y = startY + row * (cellSize + rowGap);
console.log(`预览格 [${cellIndex}] 坐标: (${x}, ${y}), 行列: (${row}, ${col}), 笔画数: ${strokes.length}`);
// 绘制完整汉字(黑色,较粗)
drawStrokes({
ctx,
strokes,
offsetX: x,
offsetY: y,
size: cellSize,
uptoInclusive: strokes.length - 1,
fillStyle: 'rgb(0,0,0)', // 黑色填充
strokeStyle: 'rgb(0,0,0)', // 黑色描边
lineWidth: 4, // 较粗的线条
});
}
/**
* 绘制练习格(逐笔画)
*/
drawPracticeCell({
ctx,
strokes,
strokeIndex,
startX,
startY,
cellSize,
colGap,
rowGap,
maxPerRow,
cellIndex
}: {
ctx: RenderingContext;
strokes: string[];
strokeIndex: number;
startX: number;
startY: number;
cellSize: number;
colGap: number;
rowGap: number;
maxPerRow: number;
cellIndex: number;
}) {
const row = Math.floor(cellIndex / maxPerRow);
const col = cellIndex % maxPerRow;
const x = startX + col * (cellSize + colGap);
const y = startY + row * (cellSize + rowGap);
console.log(`练习格 [${cellIndex}] 坐标: (${x}, ${y}), 行列: (${row}, ${col}), 笔画: ${strokeIndex + 1}/${strokes.length}`);
// 绘制到指定笔画的汉字(红色,中等粗细)
drawStrokes({
ctx,
strokes,
offsetX: x,
offsetY: y,
size: cellSize,
uptoInclusive: strokeIndex,
fillStyle: 'rgb(220, 20, 20)', // 深红色填充
strokeStyle: 'rgb(220, 20, 20)', // 深红色描边
lineWidth: 3, // 中等粗细
});
}
drawLine(linY: number) {
console.log('drawLine linY----:', linY)
const { canvas, ctx } = this;
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;