feat: 修改字母描红逻辑,添加字母手写字体

This commit is contained in:
R524809
2026-04-15 17:29:59 +08:00
parent ec5bc44741
commit 4299c4e082
62 changed files with 4135 additions and 894 deletions
-18
View File
@@ -1,18 +0,0 @@
{
"navigationBarTitleText": "练字",
"navigationBarTextStyle": "black",
"navigationBarBackgroundColor": "#FFD719",
"homeButton": true,
"backgroundColor": "#F6F6F6",
"enablePullDownRefresh": false,
"usingComponents": {
"toy-button": "/toy/button-v2/button",
"van-dialog": "@vant/weapp/dialog/index",
"word-input": "/components/word-input/word-input",
"word-card": "/components/word-card/word-card",
"word-picker": "/components/word-picker/word-picker",
"empty-state": "/components/empty-state/empty-state",
"share-guide-popup": "/components/share-guide-popup/share-guide-popup",
"add-to-miniprogram-tip": "/components/add-to-miniprogram-tip/add-to-miniprogram-tip"
}
}
-151
View File
@@ -1,151 +0,0 @@
page {
background-color: #f6f6f6;
}
.page-container {
background-color: #f6f6f6;
padding: 0 24rpx;
box-sizing: border-box;
.empty {
height: 120rpx;
}
}
.wrapper {
background-color: #ffffff;
border-radius: 20rpx;
padding: 36rpx 24rpx;
box-shadow: 0 6rpx 8rpx rgba(0, 0, 0, 0.15);
margin: 30rpx 0;
display: flex;
flex-direction: column;
.wrapper-title {
font-size: 32rpx;
color: #141414;
margin-bottom: 36rpx;
font-weight: bold;
text-align: center;
}
.word-card-box {
padding: 34rpx 0;
.word-cards-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 40rpx;
}
}
.word-input-box {
display: flex;
flex-direction: row;
justify-content: flex-start;
margin-bottom: 24rpx;
}
.action-buttons-box {
display: flex;
flex-direction: row;
justify-content: space-between;
gap: 20rpx;
margin-bottom: 24rpx;
}
}
.tianzige {
display: grid;
grid-auto-rows: min-content;
row-gap: 12rpx;
}
.tzg-row {
display: grid;
grid-template-columns: repeat(12, 1fr);
column-gap: 12rpx;
}
.tzg-cell {
position: relative;
background: #fff;
border: 4rpx solid #333;
height: 120rpx;
border-radius: 6rpx;
overflow: hidden;
}
.tzg-word {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-size: 72rpx;
color: #222;
font-family: 'Kaiti', 'KaiTi', 'STKaiti', 'FZKai-Z03S', serif;
}
.mid-line {
position: absolute;
background: repeating-linear-gradient(to right,
rgba(0, 0, 0, 0.25),
rgba(0, 0, 0, 0.25) 2rpx,
transparent 2rpx,
transparent 6rpx);
}
.mid-line.h {
left: 0;
right: 0;
top: 50%;
height: 2rpx;
transform: translateY(-50%);
}
.mid-line.v {
top: 0;
bottom: 0;
left: 50%;
width: 2rpx;
transform: translateX(-50%);
}
.empty-tip {
text-align: center;
color: #999;
font-size: 28rpx;
}
.canvas-wrapper {
display: flex;
justify-content: center;
align-items: center;
min-height: 400rpx;
background: #f8f9fa;
border-radius: 12rpx;
border: 2rpx dashed #dee2e6;
}
.canvas-content {
max-width: 100%;
border-radius: 8rpx;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.bottom-btn-box {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 120rpx;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
box-shadow: 0px -3.9rpx 5.2rpx rgba(0, 0, 0, 0.15);
padding: 0 24rpx;
box-sizing: border-box;
border-radius: 16rpx 16rpx 0 0;
}
-473
View File
@@ -1,473 +0,0 @@
import WordDrawService from '../../service/wordDrawService';
import { downloadPrint } from '../../utils/downloadPrint';
import { PAPER_SIZE } from '../../constants/colors';
import { getWordsSvgData } from '../../utils/getWordsSvgJson';
import { WORDS } from '../../constants/words';
import { CharacterItem } from '../../types/characterType';
import tracker from '../../utils/tracker';
import { defaultShareConfig } from '../../config/config';
Page({
canvas: null as Canvas | null,
ctx: null as RenderingContext | null,
wordDrawService: null as WordDrawService | null,
svgWords: {} as Record<string, string[]>,
maxRow: 0 as number,
maxCol: 0 as number,
data: {
// 最终的汉字列表(合并输入和选择的汉字)
words: [] as string[],
// 来自文本框输入的汉字(每次输入替换)
inputWords: [] as string[],
// 来自弹窗选择的汉字(追加)
selectedWords: [] as string[],
// 输入框的值(用于清空)
inputValue: '',
showSelectWordPopup: false,
showColorPopup: false,
currentKey: 0,
currentColor: '',
boxWidth: 0,
boxHeight: 0,
showShareDialog: false, // 显示分享引导弹窗
},
async onLoad() {
await this.loadSvgWords();
const hasShowPracticeDemo =
wx.getStorageSync('hasShowPracticeDemo') || false;
if (!hasShowPracticeDemo) {
const demoWords = ['好', '好', '学', '习', '天', '天', '向', '上'];
this.setData(
{
words: demoWords,
inputWords: demoWords,
selectedWords: [],
},
() => {
wx.setStorageSync('hasShowPracticeDemo', true);
},
);
}
await this.setCanvasBoxSize();
await this.initCanvas();
},
async loadSvgWords() {
try {
wx.showToast({ title: '加载字体中...', icon: 'loading' });
// 使用带缓存的SVG汉字数据获取函数
const svgWordsData = await getWordsSvgData();
this.svgWords = svgWordsData;
wx.hideToast();
console.log(
'SVG汉字数据加载成功,共',
Object.keys(this.svgWords).length,
'个汉字',
);
const { words } = this.data as any;
if (words && words.length > 0) {
this.renderPracticeContent().catch(console.error);
}
} catch (error) {
console.error('加载SVG汉字数据失败:', error);
wx.hideToast();
// 显示错误提示
wx.showModal({
title: '加载失败',
content: '无法加载汉字数据,请检查网络连接后重试',
showCancel: true,
cancelText: '取消',
confirmText: '重试',
success: (res) => {
if (res.confirm) {
// 用户点击重试,重新加载
this.loadSvgWords();
}
},
});
}
},
// 输入组件回调(所见即所得:替换文本框输入的汉字)
onConfirmInput(e: any) {
const value: string = (e && e.detail && e.detail.value) || '';
const text = (value || '').trim();
// 如果文本框为空,清空输入汉字
if (!text) {
const { selectedWords } = this.data as any;
const updatedWords = [...selectedWords];
this.setData(
{
inputWords: [],
words: updatedWords,
inputValue: '', // 同步清空输入框值
},
() => {
this.renderPracticeContent().catch(console.error);
},
);
return;
}
if (!this.isChineseText(text)) {
wx.showToast({ title: '请输入汉字', icon: 'none' });
return;
}
// 1. 解析输入的汉字
const newInputChars = this.splitToSingleChars(text);
if (newInputChars.length === 0) {
wx.showToast({ title: '请输入有效汉字', icon: 'none' });
return;
}
const { selectedWords } = this.data as any;
// 2. 检查是否超过限制(输入汉字 + 已选择的汉字)
if (newInputChars.length + selectedWords.length > 11) {
wx.showToast({
title: `最多只能添加 11 个字,当前已选择 ${selectedWords.length} 个,输入了 ${newInputChars.length}`,
icon: 'none',
duration: 3000,
});
return;
}
// 3. 替换输入汉字(不是追加),合并已选择的汉字
const updatedWords = [...newInputChars, ...selectedWords];
// 4. 更新数据并提示(同步更新 inputValue 保持一致)
this.setData(
{
inputWords: newInputChars,
words: updatedWords,
inputValue: text, // 同步输入框值
},
() => {
this.renderPracticeContent().catch(console.error);
},
);
// 5. 显示添加结果提示
wx.showToast({
title: `已更新输入汉字(${newInputChars.length} 个)`,
icon: 'none',
duration: 2000,
});
},
// 选择面板
openSelectWordPopup() {
this.setData({ showSelectWordPopup: true });
},
closeSelectWordPopup() {
this.setData({ showSelectWordPopup: false });
},
onChangeWord(e: any) {
const newSelectedWords = e.detail.selectedWords as string[];
const { inputWords } = this.data as any;
// 检查是否超过限制
if (inputWords.length + newSelectedWords.length > 11) {
wx.showToast({
title: `最多只能添加 11 个字,当前输入 ${inputWords.length} 个,选择了 ${newSelectedWords.length}`,
icon: 'none',
duration: 3000,
});
return;
}
// 合并输入汉字和选择的汉字(求并集)
const updatedWords = [...inputWords, ...newSelectedWords];
this.setData(
{
selectedWords: newSelectedWords,
words: updatedWords,
showSelectWordPopup: false,
},
() => {
if (updatedWords && updatedWords.length > 0) {
this.renderPracticeContent().catch(console.error);
}
},
);
},
// 删除(需要判断删除的是输入汉字还是选择的汉字)
deleteWordCard(e: any) {
const { key } = e.detail;
const { inputWords, selectedWords } = this.data as any;
// 判断删除的是输入汉字还是选择的汉字
if (key < inputWords.length) {
// 删除的是输入汉字
const nextInputWords = inputWords.filter(
(_: string, index: number) => index !== key,
);
const nextWords = [...nextInputWords, ...selectedWords];
this.setData(
{
inputWords: nextInputWords,
words: nextWords,
},
() => this.renderPracticeContent().catch(console.error),
);
} else {
// 删除的是选择的汉字
const selectedIndex = key - inputWords.length;
const nextSelectedWords = selectedWords.filter(
(_: string, index: number) => index !== selectedIndex,
);
const nextWords = [...inputWords, ...nextSelectedWords];
this.setData(
{
selectedWords: nextSelectedWords,
words: nextWords,
},
() => this.renderPracticeContent().catch(console.error),
);
}
},
// 清空(清空所有来源的汉字:文本框、预览、弹窗选择)
clearWords() {
// 清空所有汉字数据
this.setData(
{
words: [],
inputWords: [],
selectedWords: [],
inputValue: '', // 清空输入框
},
() => {
this.renderPracticeContent().catch(console.error);
},
);
// 关闭弹窗(如果打开)
if (this.data.showSelectWordPopup) {
this.setData({ showSelectWordPopup: false });
}
},
// 随机生成(取基础分类,过滤为可用SVG字,最多11个)
refreshWords() {
// 选取较简单的几个分类(如 0:基础独体字,1:生活高频字,2:自然与动作)
const candidate = WORDS.slice(0, 3).reduce(
(acc: string[], c: any) => acc.concat(c.words),
[] as string[],
);
// 去重
const unique = Array.from(new Set(candidate));
// 打乱
const shuffled = unique.sort(() => Math.random() - 0.5);
// 先取前 11 个
const picked = shuffled.slice(0, 10);
// 过滤为支持的SVG字
const supported = this.getSupportedWords(picked);
if (supported.length === 0) {
wx.showToast({
title: '随机到的字暂不支持,重试一下',
icon: 'none',
});
return;
}
this.setData({ words: supported }, () =>
this.renderPracticeContent().catch(console.error),
);
},
// 校验 & 分割
isChineseText(text: string): boolean {
const chineseRegex = /^[\u4e00-\u9fff]+$/;
return chineseRegex.test(text);
},
splitToSingleChars(text: string): string[] {
const chineseRegex = /[\u4e00-\u9fff]/g;
const matches = text.match(chineseRegex);
return matches || [];
},
setCanvasBoxSize() {
const query = wx.createSelectorQuery();
query
.select('#canvasWrapper')
.boundingClientRect((rect) => {
if (rect) {
const { width, height } = PAPER_SIZE['A4'];
const boxWidth = rect.width;
const boxHeight = boxWidth / (width / height);
this.setData({ boxWidth, boxHeight });
}
})
.exec();
},
async initCanvas() {
return new Promise<void>((resolve) => {
// 然后初始化canvas
wx.createSelectorQuery()
.select('#canvasContent')
.fields({
node: true,
size: true,
})
.exec(async (res) => {
if (res[0] && res[0].node) {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
if (ctx) {
this.canvas = canvas;
this.ctx = ctx;
this.wordDrawService = new WordDrawService(
canvas,
ctx,
);
// 初始化时只绘制页眉和布局
await this.wordDrawService.drawLayout();
// 绘制完成后计算并缓存最大行列数(与实际绘制一致)
const { maxRow, maxCol } =
this.wordDrawService.getMaxGridLayout();
this.maxRow = maxRow;
this.maxCol = maxCol;
// 如果有汉字数据,绘制练字内容
const { words } = this.data as any;
if (words && words.length > 0) {
await this.renderPracticeContent();
}
resolve();
}
}
});
});
},
// 绘制练字内容(只绘制田字格和汉字内容)
async renderPracticeContent() {
if (!this.canvas || !this.wordDrawService) {
await this.initCanvas();
return;
}
const { words } = this.data as any;
if (!words || words.length === 0) {
await this.wordDrawService.drawContentEmpty();
return;
}
// 检查汉字是否支持
const supportedWords = this.getSupportedWords(words);
if (supportedWords.length === 0) {
wx.showToast({ title: '暂不支持这些汉字', icon: 'none' });
await this.wordDrawService.drawContentEmpty();
return;
}
// 使用初始化阶段缓存的最大行列数;若未初始化则计算一次并缓存
let maxRow = this.maxRow;
let maxCol = this.maxCol;
if (!maxRow || !maxCol) {
const layout = this.wordDrawService!.getMaxGridLayout();
this.maxRow = layout.maxRow;
this.maxCol = layout.maxCol;
maxRow = layout.maxRow;
maxCol = layout.maxCol;
}
// 处理布局和生成练字数据(基于实际最大行列数)
const characterData = this.processCharacterLayout(
supportedWords,
maxRow,
maxCol,
);
await this.wordDrawService.drawPracticeContent(characterData);
},
/** 检查汉字是否支持,返回支持的汉字列表 */
getSupportedWords(words: string[]): string[] {
return words.filter((word) => this.svgWords[word]);
},
/** 处理汉字布局,生成练字数据 */
processCharacterLayout(
words: string[],
maxRow: number,
maxCol: number,
): CharacterItem[] {
let rowIndex = 0;
const characterData: CharacterItem[] = [];
const boundaryWords: string[] = [];
// 按顺序处理每个汉字
words.forEach((word: string) => {
const strokes = this.svgWords[word];
const strokeCount = strokes.length;
const totalCells = 1 + strokeCount + 0; // 预览格 + 练习格 + 空白格
const totalRows = Math.ceil(totalCells / maxCol);
// 这里的意思是:把这一个汉字所占的行数(totalRows)累加到 rowIndex 上。
// 这样 rowIndex 就记录了当前已经排布了多少行,用于判断是否超出了最大允许行数(maxRow)。
rowIndex = rowIndex + totalRows;
if (rowIndex <= maxRow) {
characterData.push({ character: word, strokes });
} else {
boundaryWords.push(word);
}
});
// // 提示超出页面的汉字
// if (showToast && boundaryWords.length > 0) {
// wx.showToast({
// title: `练字贴已超过一页,部分汉字未包含在本次生成结果中`,
// icon: 'none'
// });
// }
return characterData;
},
// 下载打印练字贴
async exportToPrint() {
await downloadPrint(this.canvas, {
errorToast: '请先生成练字贴',
trackerName: '练字贴',
});
},
// 分享功能
onShareAppMessage() {
// 上报分享埋点
tracker.reportShare('练字贴');
return {
...defaultShareConfig,
path: '/pages/copyBook/copyBook',
};
},
onShareTimeline() {
// 上报分享埋点
tracker.reportShare('练字贴');
return {
...defaultShareConfig,
query: '/pages/copyBook/copyBook',
};
},
/** 分享成功回调(由组件触发) */
onShareSuccess() {
// 只关闭弹窗,不触发下载
this.setData({ showShareDialog: false });
},
});
-99
View File
@@ -1,99 +0,0 @@
<view class="page-container">
<view class="wrapper">
<text class="wrapper-title">自定义练字贴</text>
<view class="word-input-box">
<word-input value="{{inputValue}}" bind:onConfirm="onConfirmInput" style="width: 100%;"/>
</view>
<view class="action-buttons-box">
<toy-button
type="green"
bind:click="openSelectWordPopup"
height="80rpx"
width="410rpx"
icon="success"
icon-class-prefix="toy-icon">
选择文字
</toy-button>
<toy-button
disabled="{{words.length <= 0}}"
type="white"
bind:click="clearWords"
width="220rpx"
height="80rpx"
icon="clear"
icon-class-prefix="toy-icon">
清空
</toy-button>
</view>
<view class="word-card-box">
<view class="word-cards-grid" wx:if="{{words.length > 0}}">
<word-card
disabledColor="{{true}}"
wx:key="index"
wx:for="{{words}}"
wx:for-item="word"
wx:for-index="index"
word="{{word}}"
key="{{index}}"
bind:onDelete="deleteWordCard"
bind:onColorTap="onColorTap" />
</view>
<empty-state
wx:if="{{!words.length}}"
title="还没有添加文字"
desc='请在上方输入文字或点击"选择文字"按钮,开始创建你的练字田字格吧!'
hint="提示:最多可以同时添加 11 个文字" />
</view>
</view>
<view id="previewWrapper" class="wrapper">
<text class="wrapper-title">预览练字田字格</text>
<view id="canvasWrapper" class="canvas-wrapper">
<canvas
type="2d"
id="canvasContent"
class="canvas-content"
style="width:{{boxWidth}}px;height:{{boxHeight}}px" />
</view>
<ad-custom unit-id="adunit-6f972b9b9bca0b9f"></ad-custom>
</view>
<view class="bottom-btn-box">
<toy-button
openType="share"
type="green"
flat="{{true}}"
bind:click="onShareAppMessage"
width="220rpx"
height="80rpx"
icon="wechat"
icon-class-prefix="toy-icon">
分享
</toy-button>
<toy-button
type="primary"
flat="{{true}}"
bind:click="exportToPrint"
width="420rpx"
height="80rpx"
icon="download"
icon-class-prefix="toy-icon">
下载打印
</toy-button>
</view>
<word-picker
show="{{showSelectWordPopup}}"
selectedWords="{{selectedWords}}"
max="11"
bind:onClose="closeSelectWordPopup"
bind:onChange="onChangeWord" />
<share-guide-popup
show="{{showShareDialog}}"
bind:onClose="onCloseShareDialog"
bind:onShareSuccess="onShareSuccess" />
<add-to-miniprogram-tip />
<view class="empty"></view>
</view>
@@ -1,11 +0,0 @@
{
"navigationBarTitleText": "专注力培养",
"navigationBarTextStyle": "black",
"navigationBarBackgroundColor": "#FFD719",
"homeButton": true,
"backgroundColor": "#F6F6F6",
"enablePullDownRefresh": false,
"usingComponents": {
"add-to-miniprogram-tip": "../../components/add-to-miniprogram-tip/add-to-miniprogram-tip"
}
}
@@ -1 +0,0 @@
@import '../mathIndex/mathIndex.less';
@@ -1,64 +0,0 @@
import { FOCUS_FUNCTION_TYPES } from '../../constants/focusFunctions';
import tracker from '../../utils/tracker';
import { defaultShareConfig } from '../../config/config';
Page({
data: {
functionList: FOCUS_FUNCTION_TYPES,
},
onLoad() {
// 页面加载
},
/**
* 打开专注力功能页面
*/
openFocusFunction(e: WechatMiniprogram.TouchEvent) {
const functionId = e.currentTarget.dataset.function;
const functionItem = this.data.functionList.find(
(item) => item.id === functionId,
);
if (!functionItem) {
return;
}
// 如果有page字段,跳转到对应页面
if (functionItem.page) {
let url = `/focusPages/${functionItem.page}/${functionItem.page}?id=${functionId}`;
// 如果有 mode 参数,添加到 URL 中
if (functionItem.mode) {
url += `&mode=${functionItem.mode}`;
}
wx.navigateTo({
url,
});
} else {
wx.showToast({
title: `功能开发中,敬请期待`,
icon: 'none',
duration: 2500,
});
}
},
onShareAppMessage() {
// 上报分享埋点
tracker.reportShare('专注力游戏');
return {
...defaultShareConfig,
path: `/pages/focusIndex/focusIndex`,
};
},
onShareTimeline() {
// 上报分享埋点
tracker.reportShare('专注力游戏');
return {
...defaultShareConfig,
query: `/pages/focusIndex/focusIndex`,
};
},
});
@@ -1,46 +0,0 @@
<view class="page-container">
<!-- 页面标题和描述 -->
<view class="math-page-header">
<!-- <view class="math-page-title">专注启蒙</view> -->
<view class="math-page-subtitle">
选择功能,生成可打印的专注力、观察力培养涂鸦卡
</view>
</view>
<!-- 功能列表 -->
<view class="math-functions-list">
<view
class="math-function-item"
wx:for="{{functionList}}"
wx:key="id"
data-function="{{item.id}}"
bind:tap="openFocusFunction"
>
<view class="function-item-img-wrapper">
<image
class="function-item-img"
src="{{item.img}}"
mode="aspectFill"
></image>
</view>
<view class="function-item-title">{{item.title}}</view>
<view class="function-item-desc">{{item.desc}}</view>
</view>
</view>
<!-- 使用提示 -->
<view class="usage-hint">
<view class="hint-icon">💡</view>
<view class="hint-text">
<view class="hint-title">使用提示</view>
<view class="hint-desc">
<view>1. 点击上方功能卡片选择要生成的涂鸦卡类型</view>
<view>2. 选择网格尺寸等参数</view>
<view>3. 预览生成的涂鸦卡效果</view>
<view>4. 下载A4格式PNG图片,打印后使用</view>
</view>
</view>
</view>
<view class="empty"></view>
<add-to-miniprogram-tip />
</view>
-23
View File
@@ -1,23 +0,0 @@
{
"navigationBarTitleText": "识字",
"navigationBarTextStyle": "black",
"navigationBarBackgroundColor": "#FFD719",
"homeButton": true,
"backgroundColor": "#F6F6F6",
"enablePullDownRefresh": false,
"usingComponents": {
"van-cell": "@vant/weapp/cell/index",
"van-icon": "@vant/weapp/icon/index",
"van-popup": "@vant/weapp/popup/index",
"van-dialog": "@vant/weapp/dialog/index",
"word-input": "../../components/word-input/word-input",
"word-card": "../../components/word-card/word-card",
"color-picker": "../../components/color-picker/color-picker",
"introduction-popup": "../../components/introduction-popup/introduction-popup",
"share-guide-popup": "../../components/share-guide-popup/share-guide-popup",
"add-to-miniprogram-tip": "../../components/add-to-miniprogram-tip/add-to-miniprogram-tip",
"toy-button": "../../toy/button-v2/button",
"word-picker": "../../components/word-picker/word-picker",
"empty-state": "../../components/empty-state/empty-state"
}
}
-177
View File
@@ -1,177 +0,0 @@
page {
background-color: #f6f6f6;
}
.page-container {
background-color: #f6f6f6;
padding: 0 24rpx;
box-sizing: border-box;
.empty {
height: 190rpx;
}
}
.wrapper {
background-color: #ffffff;
border-radius: 20rpx;
padding: 36rpx 24rpx;
box-shadow: 0 6rpx 8rpx rgba(0, 0, 0, 0.15);
margin: 30rpx 0;
display: flex;
flex-direction: column;
.wrapper-title {
font-size: 32rpx;
color: #141414;
margin-bottom: 36rpx; // 增大标题与内容间距
font-weight: bold;
text-align: center;
}
&.hidden {
visibility: hidden;
}
.word-card-box {
padding: 34rpx 0;
.word-cards-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 38rpx; // 间距从24rpx提升到32rpx
}
}
.word-input-box {
display: flex;
flex-direction: row;
justify-content: space-between;
}
.operation-box {
display: flex;
flex-direction: row;
justify-content: space-between;
}
// 模板选择区域
.template-section {
margin-top: 40rpx;
.template-title {
font-size: 28rpx;
font-weight: 600;
color: #141414;
margin-bottom: 24rpx;
text-align: center;
}
.template-list {
display: flex;
flex-direction: column;
gap: 20rpx;
}
.template-item {
background: #FFFFFF;
border: 2rpx solid #E8E8E8;
border-radius: 16rpx;
padding: 24rpx;
cursor: pointer;
transition: all 0.2s ease-in-out;
display: flex;
align-items: center;
width: 100%;
box-sizing: border-box;
&:active {
transform: scale(0.98);
}
&.active {
border-color: #93D333;
box-shadow: 0 0 0 4rpx rgba(147, 211, 51, 0.2);
}
.template-checkbox {
width: 40rpx;
height: 40rpx;
border: 2rpx solid #E8E8E8;
border-radius: 8rpx;
display: flex;
align-items: center;
justify-content: center;
margin-right: 24rpx;
flex-shrink: 0;
transition: all 0.2s ease-in-out;
.checkbox-icon {
color: #FFFFFF;
font-size: 24rpx;
font-weight: bold;
}
}
&.active .template-checkbox {
background: #93D333;
border-color: #93D333;
}
.template-name {
font-size: 28rpx;
color: #141414;
font-weight: 500;
flex: 1;
}
&.active .template-name {
color: #93D333;
font-weight: 600;
}
}
}
}
// .canvas-wrapper {
// width: 100%;
// background-color: #fff;
// box-sizing: border-box;
// }
.canvas-wrapper {
display: flex;
justify-content: center;
align-items: center;
min-height: 400rpx;
background: #f8f9fa;
border-radius: 12rpx;
border: 2rpx dashed #dee2e6;
}
.canvas-content {
max-width: 100%;
border-radius: 8rpx;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
overflow: hidden;
}
// #canvasContent {
// border: 1px solid #666;
// }
.bottom-btn-box {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 120rpx;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #fff;
box-shadow: 0px -3.9rpx 5.2rpx rgba(0, 0, 0, 0.15);
padding: 0 24rpx;
box-sizing: border-box;
border-radius: 16rpx 16rpx 0 0;
}
-475
View File
@@ -1,475 +0,0 @@
import { WATER_COLORS, PAPER_SIZE } from '../../constants/colors';
import { WORDS } from '../../constants/words';
import {
DrawServiceFactory,
IDrawService,
TemplateType,
} from '../../service/drawServiceFactory';
import { downloadPrint } from '../../utils/downloadPrint';
import tracker from '../../utils/tracker';
import { defaultShareConfig } from '../../config/config';
Page({
canvas: null as Canvas | null,
ctx: null as RenderingContext | null,
boxHeight: 0,
boxWidth: 0,
drawService: null as IDrawService | null,
data: {
cardList: [] as CardList,
selectedWords: [] as string[],
showColorPopup: false,
currentKey: 0,
currentColor: '',
showIntroductionPopup: false,
showSelectWordPopup: false, // 选择文字弹窗
selectedTemplate: 'grid', // 选中的模板类型 grid 或 find 模式
env: 'release',
isPCDevtool: false,
showShareDialog: false, // 显示分享引导弹窗
},
onLoad(options: { template?: string }) {
const { template } = options;
this.setData({
selectedTemplate: template || 'grid',
});
const hasShowIntroduction =
wx.getStorageSync('hasShowIntroduction') || false;
// 判断是否在PC端开发工具上运行
const systemInfo = wx.getDeviceInfo();
if (systemInfo.platform === 'devtools') {
this.setData({
isPCDevtool: true,
});
}
if (!hasShowIntroduction) {
this.setData(
{
cardList: [
{ color: '#FF0000', word: '涂' },
{ color: '#00FF00', word: '鸦' },
{ color: '#FF7F00', word: '丫' },
{ color: '#00FFFF', word: '欢' },
{ color: '#FFFF00', word: '迎' },
{ color: '#8A2BE2', word: '您' },
],
selectedWords: ['涂', '鸦', '丫', '欢', '迎', '您'],
// showIntroductionPopup: true,
env: getApp().globalData.env || 'release',
},
() => {
this.drawCanvas();
},
);
} else {
this.setData({
env: getApp().globalData.env || 'release',
});
}
},
onReady() {
// 当cardList为空时,canvas相关元素不会被渲染,所以不需要在这里初始化
// 尺寸计算将在initCanvas方法中进行
},
initCanvas() {
// 先获取canvasWrapper的尺寸来计算canvas尺寸
const query = wx.createSelectorQuery();
query
.select('#canvasWrapper')
.boundingClientRect((rect) => {
if (rect) {
const { width, height } = PAPER_SIZE['A4'];
const boxWidth = rect.width;
const boxHeight = boxWidth / (width / height);
// 然后初始化canvas
wx.createSelectorQuery()
.select('#canvasContent')
.fields({
node: true,
size: true,
})
.exec((res) => {
if (res[0] && res[0].node) {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
if (ctx) {
this.canvas = canvas;
this.ctx = ctx;
// 根据当前选中的模板类型创建对应的绘制服务
const templateType = this.data
.selectedTemplate as TemplateType;
this.drawService =
DrawServiceFactory.create(
templateType,
canvas,
ctx,
);
this.setData({ boxWidth, boxHeight });
// 初始化完成后,如果有cardList内容则立即绘制
const currentCardList = this.data.cardList;
if (currentCardList.length > 0) {
this.drawService
.draw(currentCardList)
.catch((err: any) => {
console.error('绘制失败:', err);
});
}
}
}
});
}
})
.exec();
},
/**
* 创建或更新绘制服务
* 根据当前选中的模板类型创建对应的服务实例
*/
createDrawService() {
if (this.canvas && this.ctx) {
const templateType = this.data.selectedTemplate as TemplateType;
this.drawService = DrawServiceFactory.create(
templateType,
this.canvas,
this.ctx,
);
}
},
/** 变更cardList 并更新canvas */
drawCanvas(
updatedCardList?: Array<{ color: string; word: string }>,
callback: () => void = () => {},
) {
if (updatedCardList) {
this.setData(
{
cardList: updatedCardList,
selectedWords: updatedCardList.map((item) => item.word),
},
() => {
// 如果cardList有内容且canvas未初始化,先初始化canvas
if (!this.canvas) {
this.initCanvas();
} else {
// 如果canvas已初始化,确保绘制服务是最新的
this.createDrawService();
}
// 如果canvas已初始化且有内容,则绘制
if (this.drawService && updatedCardList!.length > 0) {
this.drawService.draw(updatedCardList!).catch((err: any) => {
console.error('绘制失败:', err);
});
}
callback();
},
);
} else {
const currentCardList = this.data.cardList;
// 如果cardList有内容且canvas未初始化,先初始化canvas
if (!this.canvas) {
this.initCanvas();
} else {
// 如果canvas已初始化,确保绘制服务是最新的
this.createDrawService();
}
// 如果canvas已初始化且有内容,则绘制
if (this.drawService && currentCardList.length > 0) {
this.drawService.draw(currentCardList).catch((err: any) => {
console.error('绘制失败:', err);
});
}
}
},
tapCard(e: WechatMiniprogram.TouchEvent) {
const { url } = e.currentTarget.dataset;
wx.navigateTo({ url });
},
onConfirmInput(e: WechatMiniprogram.Input) {
const { cardList } = this.data;
const { value } = e.detail;
const characters = value.split('');
// 计算剩余空间
const remainingSlots = 6 - cardList.length;
if (remainingSlots <= 0) {
wx.showToast({
title: '最多只能添加6个字哦!',
icon: 'none',
duration: 2000,
});
return;
}
// 准备颜色数组
const allColors = WATER_COLORS.basic12.map((color) => color.hex);
const usedColors = cardList.map((item) => item.color);
const usedWords = cardList.map((item) => item.word);
const availableColors = allColors.filter(
(color) => !usedColors.includes(color),
);
const shuffledColors = [...availableColors].sort(
() => Math.random() - 0.5,
);
const newCharacters: string[] = [];
let isBeyond = false;
for (const char of characters) {
if (newCharacters.length >= remainingSlots) {
isBeyond = true;
break;
}
if (!usedWords.includes(char) && !newCharacters.includes(char)) {
newCharacters.push(char);
}
}
if (isBeyond) {
wx.showToast({
title: '最多只能添加6个字,多余的字未被添加哦!',
icon: 'none',
duration: 2000,
});
}
// 为新字符创建卡片
const newCards = newCharacters.map((char) => {
// 获取字对应的颜色
const colorHex = this.getColorByWord(char);
let color: string;
if (colorHex && !usedColors.includes(colorHex)) {
// 如果有对应颜色且未被使用,使用对应颜色
color = colorHex;
} else {
// 否则随机选择一个可用颜色
const randomIndex = Math.floor(
Math.random() * shuffledColors.length,
);
color = shuffledColors[randomIndex];
// 从可用颜色中移除已使用的颜色
shuffledColors.splice(randomIndex, 1);
}
return {
word: char,
color: color,
};
});
// 合并新旧卡片
const updatedCardList = [...cardList, ...newCards];
this.drawCanvas(updatedCardList);
},
deleteWordCard(e: WechatMiniprogram.CustomEvent) {
const { key, word } = e.detail;
const { cardList } = this.data;
const updatedCardList = cardList.filter((_, index) => index !== key);
this.drawCanvas(updatedCardList, () => {
wx.showToast({
title: `已删除 "${word}"`,
icon: 'none',
duration: 2000,
});
});
},
/** 下载打印 */
async exportToPrint() {
if (!this.canvas || this.data.cardList.length <= 0) {
return;
}
await downloadPrint(this.canvas, {
errorToast: '请先生成涂色卡',
trackerName: '涂色识字',
trackerMode: this.data.selectedTemplate,
});
},
/** 分享成功回调(由组件触发) */
onShareSuccess() {
this.setData({ showShareDialog: false });
},
onColorTap(e: WechatMiniprogram.CustomEvent) {
const { key, color } = e.detail;
this.setData({
showColorPopup: true,
currentKey: key,
currentColor: color,
});
},
onCloseColorPopup() {
this.setData({
showColorPopup: false,
currentKey: 0,
currentColor: '',
});
},
onChangeColor(e: WechatMiniprogram.CustomEvent) {
const { color } = e.detail;
const { currentKey, cardList } = this.data;
cardList[currentKey].color = color;
this.setData(
{
showColorPopup: false,
cardList,
},
() => {
this.drawCanvas();
},
);
},
onCloseIntroductionPopup() {
this.setData({ showIntroductionPopup: false });
wx.setStorageSync('hasShowIntroduction', true);
},
onShareAppMessage() {
// 上报分享埋点
tracker.reportShare('涂色识字');
return {
...defaultShareConfig,
path: `/pages/index/index?template=${this.data.selectedTemplate}`,
};
},
onShareTimeline() {
// 上报分享埋点
tracker.reportShare('涂色识字');
return {
...defaultShareConfig,
query: `/pages/index/index?template=${this.data.selectedTemplate}`,
};
},
clearCardList() {
// 清空cardList时,重置canvas相关引用,因为DOM元素会被移除
this.canvas = null;
this.ctx = null;
this.drawService = null;
this.drawCanvas([]);
},
// 随机生成
refreshCardList() {
// 获取前4个分类的所有文字
const allWords = WORDS.slice(0, 2).reduce((acc, category) => {
return acc.concat(category.words);
}, [] as string[]);
// 随机获取6个不重复的文字
const selectedWords: string[] = [];
while (selectedWords.length < 6) {
const randomWord =
allWords[Math.floor(Math.random() * allWords.length)];
if (!selectedWords.includes(randomWord)) {
selectedWords.push(randomWord);
}
}
// 随机获取6个不重复的颜色
const colors = [...WATER_COLORS.basic12];
const selectedColors: string[] = [];
while (selectedColors.length < 6) {
const randomIndex = Math.floor(Math.random() * colors.length);
const color = colors.splice(randomIndex, 1)[0];
selectedColors.push(color.hex);
}
// 组合文字和颜色
const cardList = selectedWords.map((word, index) => ({
color: selectedColors[index],
word,
}));
this.drawCanvas(cardList);
},
openSelectWordPopup() {
this.setData({
showSelectWordPopup: true,
});
},
closeSelectWordPopup() {
this.setData({
showSelectWordPopup: false,
});
},
// 获取颜色字对应的16进制颜色值
getColorByWord(word: string): string | null {
const colorMap: Record<string, string> = {
: '#FF0000',
: '#0000FF',
绿: '#00FF00',
: '#FFFF00',
: '#000000',
: '#FFFFFF',
: '#800080',
: '#FF7F00',
: '#FF69B4',
: '#A52A2A',
: '#808080',
};
return colorMap[word] || null;
},
onChangeWord(e: WechatMiniprogram.CustomEvent) {
const selectedWords = e.detail.selectedWords as string[];
const colors = [...WATER_COLORS.basic12];
const cardList = selectedWords.map((word, index) => {
const colorHex = this.getColorByWord(word);
return {
color: colorHex || colors[index].hex,
word,
};
});
this.setData({ showSelectWordPopup: false });
this.drawCanvas(cardList);
},
onDebugEntryTap() {
wx.navigateTo({
url: '/pages/debug/debug',
});
},
// 模板选择事件
onSelectTemplate(e: WechatMiniprogram.TouchEvent) {
const { template } = e.currentTarget.dataset;
this.setData(
{
selectedTemplate: template,
},
() => {
// 模板切换后,重新创建绘制服务并重新绘制
if (this.canvas && this.ctx) {
this.createDrawService();
// 如果有文字卡片,重新绘制canvas
if (this.data.cardList.length > 0) {
this.drawCanvas();
}
}
},
);
},
});
-146
View File
@@ -1,146 +0,0 @@
<view class="page-container">
<view class="wrapper">
<text class="wrapper-title">自定义涂鸦卡</text>
<view class="word-input-box">
<word-input bind:onConfirm="onConfirmInput" width="410rpx" />
<toy-button
type="green"
bind:click="openSelectWordPopup"
width="200rpx">
选择文字
</toy-button>
</view>
<view class="word-card-box">
<view class="word-cards-grid" wx:if="{{cardList.length > 0}}">
<word-card
wx:key="index"
wx:for="{{cardList}}"
wx:for-item="item"
wx:for-index="index"
key="{{index}}"
word="{{item.word}}"
color="{{item.color}}"
bind:onDelete="deleteWordCard"
bind:onColorTap="onColorTap" />
</view>
<empty-state
wx:if="{{!cardList.length}}"
title="还没有添加文字"
desc="请在上方输入文字或点击“选择文字”按钮,开始创建你的涂鸦卡吧!"
hint="提示:最多可以同时添加 6 个文字" />
</view>
<view class="operation-box">
<toy-button
type="primary"
bind:click="refreshCardList"
width="410rpx"
icon="refresh"
icon-class-prefix="toy-icon">
随机生成
</toy-button>
<toy-button
disabled="{{cardList.length <= 0}}"
type="white"
bind:click="clearCardList"
width="200rpx"
icon="clear"
icon-class-prefix="toy-icon">
清空
</toy-button>
</view>
<!-- 趣味模板选择区域 -->
<view class="template-section">
<view class="template-title">选择涂色模板</view>
<view class="template-list">
<view
class="template-item {{selectedTemplate === 'grid' ? 'active' : ''}}"
data-template="grid"
bind:tap="onSelectTemplate">
<view class="template-checkbox">
<view
class="checkbox-icon"
wx:if="{{selectedTemplate === 'grid'}}"
>✓</view
>
</view>
<view class="template-name">网格模板</view>
</view>
<view
class="template-item {{selectedTemplate === 'find' ? 'active' : ''}}"
data-template="find"
bind:tap="onSelectTemplate">
<view class="template-checkbox">
<view
class="checkbox-icon"
wx:if="{{selectedTemplate === 'find'}}"
>✓</view
>
</view>
<view class="template-name">找字模板</view>
</view>
</view>
<ad-custom unit-id="adunit-4efb537f971b3f7d"></ad-custom>
</view>
</view>
<view id="previewWrapper" class="wrapper" wx:if="{{cardList.length > 0}}">
<text class="wrapper-title">预览打印效果</text>
<view id="canvasWrapper" class="canvas-wrapper">
<canvas
type="2d"
id="canvasContent"
class="canvas-content"
style="width:{{boxWidth}}px;height:{{boxHeight}}px" />
</view>
</view>
<van-cell
wx:if="{{env !== 'release'}}"
is-link
title="debug页面"
link-type="navigateTo"
url="/pages/debug/debug" />
<view class="empty"></view>
<color-picker
show="{{showColorPopup}}"
currentColor="{{currentColor}}"
bind:onClose="onCloseColorPopup"
bind:onChange="onChangeColor" />
<word-picker
show="{{showSelectWordPopup}}"
cardList="{{cardList}}"
bind:onClose="closeSelectWordPopup"
bind:onChange="onChangeWord" />
</view>
<view class="bottom-btn-box">
<toy-button
openType="share"
type="green"
flat="{{true}}"
bind:click="onShareAppMessage"
width="220rpx"
height="80rpx"
icon="wechat"
icon-class-prefix="toy-icon">
分享
</toy-button>
<toy-button
type="primary"
flat="{{true}}"
bind:click="exportToPrint"
width="420rpx"
height="80rpx"
disabled="{{cardList.length <= 0}}"
icon="download"
icon-class-prefix="toy-icon">
下载打印
</toy-button>
</view>
<introduction-popup
wx:if="{{showIntroductionPopup}}"
bind:onClose="onCloseIntroductionPopup" />
<share-guide-popup
show="{{showShareDialog}}"
bind:onClose="onCloseShareDialog"
bind:onShareSuccess="onShareSuccess" />
<add-to-miniprogram-tip />
@@ -1,11 +0,0 @@
{
"navigationBarTitleText": "数感启蒙",
"navigationBarTextStyle": "black",
"navigationBarBackgroundColor": "#FFD719",
"homeButton": true,
"backgroundColor": "#F6F6F6",
"enablePullDownRefresh": false,
"usingComponents": {
"add-to-miniprogram-tip": "../../components/add-to-miniprogram-tip/add-to-miniprogram-tip"
}
}
-161
View File
@@ -1,161 +0,0 @@
page {
background-color: #f6f6f6;
}
.page-container {
background-color: #f6f6f6;
padding: 0 24rpx;
box-sizing: border-box;
.empty {
height: 190rpx;
}
}
/* 数学页面标题和描述 */
.math-page-header {
text-align: center;
padding: 28rpx 0;
}
.math-page-title {
font-size: 36rpx;
font-weight: 600;
color: #141414;
margin-bottom: 16rpx;
}
.math-page-subtitle {
font-size: 24rpx;
color: #666666;
line-height: 1.5;
}
/* 数学功能列表样式 - 两列瀑布流 */
.math-functions-list {
display: flex;
flex-direction: row;
flex-wrap: wrap;
gap: 22rpx;
margin-bottom: 40rpx;
}
.math-function-item {
background: #ffffff;
border: 2rpx solid #e8e8e8;
border-radius: 24rpx;
padding: 24rpx;
display: flex;
flex-direction: column;
align-items: center;
gap: 18rpx;
flex: 0 0 calc(50% - 12rpx);
box-sizing: border-box;
transition: all 0.2s ease-in-out;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 24rpx;
opacity: 0;
background: rgba(147, 211, 51, 0.1);
transition: opacity 0.2s ease-in-out;
}
&:active {
&::after {
opacity: 1;
}
border-color: #93d333;
box-shadow: 0 8rpx 24rpx rgba(147, 211, 51, 0.2);
}
}
.function-item-img-wrapper {
width: 100%;
height: 310rpx;
flex-shrink: 0;
position: relative;
z-index: 1;
border-radius: 16rpx;
overflow: hidden;
background-color: #f5f5f5;
// border: 1rpx solid #e8e8e8;
}
.function-item-img {
width: 100%;
height: 100%;
display: block;
}
.function-item-title {
font-size: 30rpx;
font-weight: 600;
color: #141414;
line-height: 1.4;
text-align: left;
position: relative;
z-index: 1;
width: 100%;
margin-top: 4rpx;
}
.function-item-desc {
font-size: 24rpx;
color: #666666;
line-height: 1.5;
text-align: left;
position: relative;
z-index: 1;
width: 100%;
}
/* 使用提示 */
.usage-hint {
background: linear-gradient(135deg, #fff7e6 0%, #fffbe6 100%);
border: 2rpx solid #ffd719;
border-radius: 24rpx;
padding: 32rpx;
display: flex;
align-items: flex-start;
gap: 24rpx;
box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}
.hint-icon {
font-size: 40rpx;
flex-shrink: 0;
}
.hint-text {
flex: 1;
}
.hint-title {
font-size: 28rpx;
font-weight: 600;
color: #141414;
margin-bottom: 8rpx;
}
.hint-desc {
font-size: 24rpx;
color: #666666;
line-height: 1.5;
view {
margin-bottom: 8rpx;
&:last-child {
margin-bottom: 0;
}
}
}
-59
View File
@@ -1,59 +0,0 @@
import { MATH_FUNCTION_TYPES } from '../../constants/mathFunctions';
import tracker from '../../utils/tracker';
import { defaultShareConfig } from '../../config/config';
Page({
data: {
functionList: MATH_FUNCTION_TYPES,
},
onLoad() {
// 页面加载
},
/**
* 打开数学功能页面
*/
openMathFunction(e: WechatMiniprogram.TouchEvent) {
const functionId = e.currentTarget.dataset.function;
const functionItem = this.data.functionList.find(
(item) => item.id === functionId,
);
if (!functionItem) {
return;
}
// 如果有page字段,跳转到对应页面
if (functionItem.page) {
wx.navigateTo({
url: `/mathPages/${functionItem.page}/${functionItem.page}?id=${functionId}`,
});
} else {
wx.showToast({
title: `功能开发中,敬请期待`,
icon: 'none',
duration: 2500,
});
}
},
onShareAppMessage() {
// 上报分享埋点
tracker.reportShare('数感启蒙');
return {
...defaultShareConfig,
path: `/pages/mathIndex/mathIndex`,
};
},
onShareTimeline() {
// 上报分享埋点
tracker.reportShare('数感启蒙');
return {
...defaultShareConfig,
query: `/pages/mathIndex/mathIndex`,
};
},
});
@@ -1,46 +0,0 @@
<view class="page-container">
<!-- 页面标题和描述 -->
<view class="math-page-header">
<!-- <view class="math-page-title">数感启蒙</view> -->
<view class="math-page-subtitle">
选择功能,生成可打印的数感启蒙涂鸦卡
</view>
</view>
<!-- 功能列表 -->
<view class="math-functions-list">
<view
class="math-function-item"
wx:for="{{functionList}}"
wx:key="id"
data-function="{{item.id}}"
bind:tap="openMathFunction"
>
<view class="function-item-img-wrapper">
<image
class="function-item-img"
src="{{item.img}}"
mode="aspectFill"
></image>
</view>
<view class="function-item-title">{{item.title}}</view>
<view class="function-item-desc">{{item.desc}}</view>
</view>
</view>
<!-- 使用提示 -->
<view class="usage-hint">
<view class="hint-icon">💡</view>
<view class="hint-text">
<view class="hint-title">使用提示</view>
<view class="hint-desc">
<view>1. 点击上方功能卡片选择要生成的涂鸦卡类型</view>
<view>2. 选择数字等参数</view>
<view>3. 预览生成的涂鸦卡效果</view>
<view>4. 下载A4格式PNG图片,打印后使用</view>
</view>
</view>
</view>
<view class="empty"></view>
<add-to-miniprogram-tip />
</view>