更改描述
在现有 Bingo 宾果制品基础上,新增「导出图片」功能,让用户勾选完成后可以把棋盘保存成图片。保持现有所有功能、样式、存储逻辑不变,不引入任何外部库(用原生 Canvas 绘制,不要用 html2canvas)。
## 按钮与位置
- 在 .actions 按钮行中,「复制结果」旁新增主按钮「导出图片」(id="exportBtn",class="btn btn-primary")。
- 在 #note 与 #fallback 之间新增一个导出预览区 <div id="exportPanel" class="export-panel" hidden>,包含:
- 一行说明文字:「图片已生成。若没有自动下载,请长按(手机)或右键(电脑)图片保存。」
- <img id="exportImg" class="export-img" alt="Bingo 结果图片">(max-width:100%,height:auto,细黑边框,小圆角)
- 按钮行:「下载图片」(id="downloadBtn",再次触发下载)、「复制图片」(id="copyImgBtn",仅在 navigator.clipboard 与 ClipboardItem 可用时显示,使用 navigator.clipboard.write([new ClipboardItem({'image/png': blob})]),失败时用 #note 提示「当前环境不能直接复制图片,请长按/右键保存」)、「关闭预览」(id="closeExportBtn")。
- 样式沿用现有 CSS 变量,深色模式下也正常显示;按钮 focus 样式与现有一致。
- 点击「导出图片」后:生成 PNG → 显示预览区(并 scrollIntoView({block:'nearest'}),reduce-motion 时不用 smooth)→ 尝试自动触发下载(创建 <a download="bingo-YYYYMMDD-HHmm.png"> 的 blob URL 并 click,用 try/catch 包裹,沙箱禁止下载时静默失败,预览图作为后备)→ 用 setNote 提示「图片已生成」。blob URL 在重新生成或关闭时 URL.revokeObjectURL。若 canvas.toBlob 不可用或返回 null,则退回 canvas.toDataURL('image/png') 作为 img.src。整个流程用 try/catch,出错时 setNote('导出失败,请改用「复制结果」')。
- 勾选/题目变化后,若预览区正在显示,则隐藏它(避免图片过时),或在点击导出时重新生成。
## 图片绘制规格(Canvas,固定浅色纸张风格,不随系统深色模式变化,便于分享)
- 逻辑尺寸 1080 px 宽,按 Math.min(2, devicePixelRatio||1) 的倍率放大 canvas 像素(最终清晰),高度根据内容计算(标题区 + 5×5 棋盘 + 底部信息区)。
- 背景 #fffdf8,四周留 40px 边距。
- 顶部:居中大标题(state.title,粗宋体栈 "Songti SC","Noto Serif CJK SC","SimSun",serif,weight 900,约 64px,过长自动缩小或换行);副标题(若有,即预设 A/B 的 subtitle)灰色 #555 粗体约 26px,自动按宽度换行居中;若 els.player 可见,则在标题上方小字显示「玩家:用户名」。
- 棋盘:5×5,格子间距 6px,每格正方形,白底 #fff,1.5~2px 黑色 #111 边框,小圆角 4px。格内文字居中,字体 system-ui/"PingFang SC"/"Microsoft YaHei"/sans-serif,weight 600,根据文字长度自适应字号(从 26px 向下到最小 16px,直到按字符逐个测量 measureText 换行后能放进格子内,留 8px 内边距;使用 Array.from 按字符拆行以支持中文无空格换行);文字垂直居中。
- 已勾选格:文字略降低透明度(0.7),并在格子中央叠加大号紫红色 #d6246e 手绘风对勾"✓"(字体 "Segoe Script","Bradley Hand","Marker Felt","Comic Sans MS",cursive,约格宽的 0.75 倍,旋转 -12°,加粗,带细白色描边 3px 保证可读)。
- 连线上的格子:底色 #e3f6e8,边框 #2e9e4f 加粗 4px,左上角绘制小图标 "✦"(绿色),不能只靠颜色。
- 若有连线,在标题与棋盘之间(或棋盘下方)绘制一个绿色 #1f7a3a 圆角胶囊,白色粗体字「Bingo! ×连线数」,略微旋转 -4°。
- 底部信息区:居中一行「已勾 N / 25 格 · 连线 M 条」(粗体约 30px);其下一行灰色小字「仅供娱乐连线,不能用于判断任何健康状况。」(约 20px)。不要再添加其他免责声明。
- 所有文本通过 canvas fillText 绘制,不涉及 innerHTML。
## 实现要点
- 新增 els.exportBtn / exportPanel / exportImg / downloadBtn / copyImgBtn / closeExportBtn 引用,事件监听写在现有 IIFE 内,风格与现有代码一致(ES5 风格 var/function 亦可)。
- 提供函数 drawResultCanvas() 返回 canvas;函数 wrapText(ctx, text, maxWidth) 返回行数组;函数 roundRect(ctx,x,y,w,h,r) 自行实现(不依赖 ctx.roundRect)。
- 用 document.fonts && document.fonts.ready 等待(可选,有超时保护,不阻塞)。
- 无障碍:按钮有明确文字;预览图有 alt;导出后用 setNote(aria-live)通知。
- 响应式:360px 宽下按钮自动换行,预览图不溢出。
查看更改
HTML Changes
<div id="app">
<header class="head">
<p id="player" class="player" hidden></p>
<h1 id="title" class="title">ADHD Bingo</h1>
<p id="subtitle" class="subtitle"></p>
</header>
<div class="toolbar">
<label for="preset" class="toolbar-label">题目:</label>
<select id="preset" class="select">
<option value="A">ADHD Bingo(梗图原版)</option>
<option value="B">日常小 Bingo</option>
<option value="custom" id="customOption" disabled>自定义题目</option>
</select>
</div>
<div class="status-wrap">
<div id="status" class="status" aria-live="polite">
<span id="statusText">已勾 0 / 25 格 · 连线 0 条</span>
<span id="bingoBadge" class="bingo-badge" hidden>Bingo!</span>
</div>
</div>
<div class="board-wrap">
<div id="board" class="board" role="group" aria-label="Bingo 棋盘,5 行 5 列"></div>
<div id="fx" class="fx" aria-hidden="true"></div>
</div>
<div class="actions">
<button type="button" id="clearBtn" class="btn">清空勾选</button>
<button type="button" id="shuffleBtn" class="btn">随机打乱格子位置</button>
<button type="button" id="copyBtn" class="btn btn-primary">复制结果</button>
+ <button type="button" id="exportBtn" class="btn btn-primary">导出图片</button>
</div>
<p id="note" class="note" aria-live="polite"></p>
+ <div id="exportPanel" class="export-panel" hidden>
+ <p class="export-tip">图片已生成。若没有自动下载,请长按(手机)或右键(电脑)图片保存。</p>
+ <img id="exportImg" class="export-img" alt="Bingo 结果图片">
+ <div class="export-actions">
+ <button type="button" id="downloadBtn" class="btn">下载图片</button>
+ <button type="button" id="copyImgBtn" class="btn" hidden>复制图片</button>
+ <button type="button" id="closeExportBtn" class="btn">关闭预览</button>
+ </div>
+ </div>
+
<div id="fallback" class="fallback" hidden>
<label for="fallbackText" class="fallback-label">复制文本(可全选)</label>
<textarea id="fallbackText" class="textarea" rows="8" readonly></textarea>
</div>
<details id="customPanel" class="panel">
<summary>自定义题目</summary>
<div class="panel-body">
<label for="customTitle" class="field-label">标题</label>
<input id="customTitle" class="input" type="text" maxlength="30" placeholder="例如:我的周末 Bingo" autocomplete="off">
<label for="customText" class="field-label">题目(每行一项,必须正好 25 行,每项不超过 40 字)</label>
<textarea id="customText" class="textarea" rows="10" placeholder="每行写一项,共 25 行"></textarea>
<div class="panel-actions">
<button type="button" id="applyBtn" class="btn btn-primary">套用</button>
<button type="button" id="fillBtn" class="btn">填入当前题目</button>
</div>
<p id="customError" class="error" aria-live="polite"></p>
</div>
</details>
<p class="footer">仅供娱乐连线,不能用于判断任何健康状况。</p>
</div>
CSS Changes
#app {
--paper: #fffdf8;
--ink: #111111;
--muted: #555555;
--cell-bg: #ffffff;
--cell-hover: #fff1f6;
--mark: #d6246e;
--line: #2e9e4f;
--line-bg: #e3f6e8;
--badge: #1f7a3a;
--focus: #2563eb;
--error: #c62828;
--soft: #f1ede3;
box-sizing: border-box;
max-width: 600px;
margin: 0 auto;
padding: 16px 12px 24px;
background: var(--paper);
color: var(--ink);
font-family: system-ui, -apple-system, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
line-height: 1.5;
}
#app *,
#app *::before,
#app *::after {
box-sizing: border-box;
}
#app [hidden] {
display: none !important;
}
@media (prefers-color-scheme: dark) {
#app {
--paper: #14151a;
--ink: #f2f2f2;
--muted: #b5b8c2;
--cell-bg: #1d1f26;
--cell-hover: #2b2030;
--mark: #ff4f86;
--line: #52d17a;
--line-bg: #173823;
--badge: #1f7a3a;
--focus: #7aa7ff;
--error: #ff8a80;
--soft: #23252d;
}
}
#app .head {
text-align: center;
margin-bottom: 10px;
}
#app .player {
margin: 0 0 4px;
font-size: 0.75rem;
color: var(--muted);
}
#app .title {
margin: 0;
font-family: "Songti SC", "Noto Serif CJK SC", "Noto Serif SC", "SimSun", system-ui, sans-serif;
font-weight: 900;
font-size: clamp(1.9rem, 8vw, 3rem);
line-height: 1.15;
letter-spacing: 0.02em;
overflow-wrap: anywhere;
}
#app .subtitle {
margin: 6px 0 0;
font-size: clamp(0.8rem, 3.2vw, 0.95rem);
font-weight: 700;
color: var(--muted);
overflow-wrap: anywhere;
}
#app .toolbar {
display: flex;
align-items: center;
gap: 8px;
margin: 12px 0 8px;
}
#app .toolbar-label {
font-size: 0.9rem;
font-weight: 700;
white-space: nowrap;
}
#app .select,
#app .input,
#app .textarea {
font: inherit;
font-size: 0.9rem;
color: var(--ink);
background: var(--cell-bg);
border: 1.5px solid var(--ink);
border-radius: 4px;
padding: 0.4em 0.6em;
}
#app .select {
flex: 1;
min-width: 0;
}
#app .input,
#app .textarea {
width: 100%;
display: block;
}
#app .textarea {
resize: vertical;
line-height: 1.5;
}
#app .select:focus-visible,
#app .input:focus-visible,
#app .textarea:focus-visible,
#app .btn:focus-visible,
#app .panel summary:focus-visible {
outline: 3px solid var(--focus);
outline-offset: 2px;
}
#app .status-wrap {
margin: 8px 0;
min-height: 2.2rem;
}
#app .status {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 10px;
font-weight: 800;
font-size: clamp(0.9rem, 3.6vw, 1.05rem);
}
#app .bingo-badge {
display: inline-block;
padding: 0.1em 0.7em;
background: var(--badge);
color: #ffffff;
border-radius: 999px;
font-weight: 900;
letter-spacing: 0.05em;
transform: rotate(-4deg);
}
#app .bingo-badge.pulse {
animation: bingoShine 1.1s ease-out 1;
}
@keyframes bingoShine {
0% { transform: rotate(-4deg) scale(0.4); box-shadow: 0 0 0 0 rgba(255, 210, 60, 0.9); }
40% { transform: rotate(-6deg) scale(1.25); box-shadow: 0 0 0 10px rgba(255, 210, 60, 0.35); }
100% { transform: rotate(-4deg) scale(1); box-shadow: 0 0 0 18px rgba(255, 210, 60, 0); }
}
#app .board-wrap {
position: relative;
}
#app .board {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 4px;
}
#app .cell {
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
aspect-ratio: 1 / 1;
padding: 3px;
margin: 0;
background: var(--cell-bg);
color: var(--ink);
border: 1.5px solid var(--ink);
border-radius: 3px;
font: inherit;
font-size: clamp(0.6rem, 0.2rem + 1.6vw, 0.92rem);
font-weight: 600;
line-height: 1.25;
text-align: center;
cursor: pointer;
overflow-wrap: anywhere;
word-break: break-word;
transition: transform 0.12s ease, background-color 0.12s ease, box-shadow 0.12s ease;
-webkit-tap-highlight-color: transparent;
}
#app .cell:hover {
transform: translateY(-2px);
background: var(--cell-hover);
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.18);
z-index: 1;
}
#app .cell:focus-visible {
outline: 3px solid var(--focus);
outline-offset: 1px;
z-index: 2;
}
#app .cell .txt {
position: relative;
display: block;
max-width: 100%;
overflow-wrap: anywhere;
}
#app .cell[aria-pressed="true"] .txt {
opacity: 0.7;
}
#app .cell .mark {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
font-family: "Segoe Script", "Bradley Hand", "Marker Felt", "Comic Sans MS", cursive, system-ui, sans-serif;
font-size: clamp(2.2rem, 11vw, 4.2rem);
font-weight: 900;
line-height: 1;
color: var(--mark);
transform: rotate(-12deg);
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.55);
pointer-events: none;
}
#app .cell[aria-pressed="true"] .mark {
display: flex;
animation: markPop 0.28s cubic-bezier(0.2, 1.4, 0.4, 1) 1;
}
@keyframes markPop {
0% { transform: rotate(-12deg) scale(0); opacity: 0; }
60% { transform: rotate(-16deg) scale(1.35); opacity: 1; }
100% { transform: rotate(-12deg) scale(1); opacity: 1; }
}
#app .cell.line {
background: var(--line-bg);
border-color: var(--line);
box-shadow: inset 0 0 0 3px var(--line);
}
#app .cell.line:hover {
background: var(--line-bg);
}
#app .cell.line::after {
content: "✦";
position: absolute;
top: 2px;
left: 4px;
font-size: 0.8rem;
line-height: 1;
color: var(--line);
pointer-events: none;
}
#app .fx {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 5;
}
#app .fx i {
position: absolute;
top: -12px;
left: var(--x);
width: 8px;
height: 12px;
background: var(--c);
border-radius: 1px;
opacity: 0;
animation: confettiFall 1.5s ease-out forwards;
animation-delay: var(--d);
}
@keyframes confettiFall {
0% { opacity: 1; transform: translate(0, 0) rotate(0deg); }
100% { opacity: 0; transform: translate(var(--dx), 300px) rotate(var(--r)); }
}
#app .actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: center;
margin: 14px 0 6px;
}
#app .btn {
font: inherit;
font-size: 0.9rem;
font-weight: 700;
padding: 0.5em 1em;
background: var(--cell-bg);
color: var(--ink);
border: 1.5px solid var(--ink);
border-radius: 4px;
cursor: pointer;
transition: transform 0.12s ease, background-color 0.12s ease;
}
#app .btn:hover {
transform: translateY(-1px);
background: var(--cell-hover);
}
#app .btn:active {
transform: translateY(0);
}
#app .btn-primary {
background: var(--ink);
color: var(--paper);
}
#app .btn-primary:hover {
background: var(--ink);
opacity: 0.88;
}
#app .note {
min-height: 1.4em;
margin: 4px 0;
text-align: center;
font-size: 0.85rem;
color: var(--muted);
}
#app .fallback {
margin: 8px 0;
}
#app .fallback-label,
#app .field-label {
display: block;
margin: 10px 0 4px;
font-size: 0.85rem;
font-weight: 700;
}
#app .panel {
margin-top: 14px;
border: 1.5px solid var(--ink);
border-radius: 4px;
background: var(--soft);
}
#app .panel summary {
padding: 0.6em 0.9em;
font-weight: 800;
cursor: pointer;
}
#app .panel-body {
padding: 0 0.9em 0.9em;
}
#app .panel-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
#app .error {
min-height: 1.4em;
margin: 8px 0 0;
font-size: 0.85rem;
font-weight: 700;
color: var(--error);
}
#app .footer {
margin: 18px 0 0;
text-align: center;
font-size: 0.72rem;
color: var(--muted);
}
+#app .export-panel {
+ margin: 10px 0;
+ padding: 10px;
+ border: 1.5px solid var(--ink);
+ border-radius: 4px;
+ background: var(--soft);
+ text-align: center;
+}
+
+#app .export-tip {
+ margin: 0 0 8px;
+ font-size: 0.85rem;
+ font-weight: 700;
+ color: var(--muted);
+}
+
+#app .export-img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+ margin: 0 auto;
+ border: 1px solid var(--ink);
+ border-radius: 4px;
+ background: #fffdf8;
+}
+
+#app .export-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ justify-content: center;
+ margin-top: 10px;
+}
+
@media (prefers-reduced-motion: reduce) {
#app *,
#app *::before,
#app *::after {
animation: none !important;
transition: none !important;
}
#app .cell:hover,
#app .btn:hover {
transform: none;
}
}
JS Changes
(function () {
'use strict';
var SIZE = 25;
var COLS = 5;
var STORE_KEY = 'bingo_state_v1';
var PRESETS = {
A: {
title: 'ADHD Bingo',
subtitle: '五个连成一线你很可能是ADHD患者(梗图原文,仅供娱乐)',
items: [
'找有趣的事做而造成过很多损失',
'小动作(摸头发、咬指甲、晃身体、搓手指等)',
'容易被学校或公司处罚甚至开除',
'容易和人起冲突',
'吃垃圾食品饮料多于常人',
'语速快、结巴、听不清',
'打断别人说话或插嘴他人谈话',
'没有规则意识常常违反纪律',
'手脚动作不停',
'摔伤、磕伤、碰伤',
'比别人先注意到周围的风吹草动',
'训斥和打骂几乎不起作用',
'做自己觉得枯燥的事时难以集中注意力',
'忘掉了(忘带了、忘拿了、忘弄了、忘做了)',
'入睡困难、入睡前会胡思乱想',
'常常忽略细节粗心大意',
'丢东西',
'对于管理人员而言是极大的麻烦',
'冲动、暴躁、大吼大叫',
'不分时间场合做不该做的事',
'社交问题、朋友少甚至没有',
'过度沉迷于自己觉得有意思的事',
'做不完作业做不完工作',
'思维发散、跳跃、创造力丰富',
'“思绪已然飘向远方”'
]
},
B: {
title: '日常小 Bingo',
subtitle: '轻松无害的日常小梗,看看你中了几个',
items: [
'进房间忘了要干嘛',
'找手机时手里正拿着手机',
'开了一大堆浏览器标签页',
'待办清单里还有“写待办”',
'买了漂亮本子舍不得用',
'截止前一刻突然开工',
'一句歌词单曲循环一整天',
'想早睡却又刷了一眼手机',
'泡了茶忘了喝,凉了',
'洗衣机洗完忘了晾',
'明明很困却不想睡觉',
'同时在看三本书都没看完',
'出门后又折返回家拿东西',
'说“就五分钟”然后过了一小时',
'买了课程或软件却没打开过',
'收藏夹里的东西从没回看过',
'对着空白文档发呆',
'突然想打扫,结果开始整理别的',
'想回的消息拖了好几天',
'在冰箱前站了很久不知道吃什么',
'耳机线总是缠成一团',
'把东西放在“安全的地方”然后找不到',
'下载了一堆没看的文章',
'聊着聊着话题跑到十万八千里',
'想起一件事,打开手机却忘了是什么'
]
}
};
var LINES = (function () {
var res = [];
var r, c, row, col;
for (r = 0; r < 5; r++) {
row = [];
for (c = 0; c < 5; c++) row.push(r * 5 + c);
res.push(row);
}
for (c = 0; c < 5; c++) {
col = [];
for (r = 0; r < 5; r++) col.push(r * 5 + c);
res.push(col);
}
res.push([0, 6, 12, 18, 24]);
res.push([4, 8, 12, 16, 20]);
return res;
})();
function $(id) { return document.getElementById(id); }
var els = {
player: $('player'),
title: $('title'),
subtitle: $('subtitle'),
preset: $('preset'),
customOption: $('customOption'),
statusText: $('statusText'),
bingoBadge: $('bingoBadge'),
board: $('board'),
fx: $('fx'),
clearBtn: $('clearBtn'),
shuffleBtn: $('shuffleBtn'),
copyBtn: $('copyBtn'),
note: $('note'),
fallback: $('fallback'),
fallbackText: $('fallbackText'),
customPanel: $('customPanel'),
customTitle: $('customTitle'),
customText: $('customText'),
applyBtn: $('applyBtn'),
fillBtn: $('fillBtn'),
+ customError: $('customError'),
+ exportBtn: $('exportBtn'),
+ exportPanel: $('exportPanel'),
+ exportImg: $('exportImg'),
+ downloadBtn: $('downloadBtn'),
+ copyImgBtn: $('copyImgBtn'),
+ closeExportBtn: $('closeExportBtn')
- customError: $('customError')
};
if (!els.board) return;
var reduceMotion = window.matchMedia ? window.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false };
function emptyChecked() {
var a = [];
for (var i = 0; i < SIZE; i++) a.push(false);
return a;
}
function presetState(mode) {
var p = PRESETS[mode] || PRESETS.A;
return {
mode: PRESETS[mode] ? mode : 'A',
title: p.title,
items: p.items.slice(),
checked: emptyChecked()
};
}
var state = presetState('A');
var cells = [];
var dirty = false;
var noteTimer = null;
var fxTimer = null;
var badgeTimer = null;
/* ---------- storage (silent fallback) ---------- */
function withTimeout(promise, ms) {
return new Promise(function (resolve) {
var done = false;
var t = setTimeout(function () {
if (!done) { done = true; resolve(null); }
}, ms);
Promise.resolve(promise).then(function (v) {
if (!done) { done = true; clearTimeout(t); resolve(v); }
}, function () {
if (!done) { done = true; clearTimeout(t); resolve(null); }
});
});
}
function storageGet(key) {
try {
if (window.discourseArtifact && typeof window.discourseArtifact.get === 'function') {
return withTimeout(window.discourseArtifact.get(key), 3000);
}
} catch (e) { /* ignore */ }
return Promise.resolve(null);
}
var saveChain = Promise.resolve();
function storageSet(key, value) {
saveChain = saveChain.then(function () {
try {
if (window.discourseArtifact && typeof window.discourseArtifact.set === 'function') {
return withTimeout(window.discourseArtifact.set(key, value), 3000);
}
} catch (e) { /* ignore */ }
return null;
}).catch(function () { return null; });
}
function saveState() {
try {
storageSet(STORE_KEY, JSON.stringify({
mode: state.mode,
title: state.title,
items: state.items,
checked: state.checked
}));
} catch (e) { /* ignore */ }
}
function sanitize(raw) {
try {
var o = JSON.parse(raw);
if (!o || !Array.isArray(o.items) || o.items.length !== SIZE) return null;
if (!Array.isArray(o.checked) || o.checked.length !== SIZE) return null;
var mode = (o.mode === 'A' || o.mode === 'B' || o.mode === 'custom') ? o.mode : 'custom';
return {
mode: mode,
title: String(o.title || 'Bingo').slice(0, 60),
items: o.items.map(function (x) { return String(x).slice(0, 80); }),
checked: o.checked.map(function (x) { return !!x; })
};
} catch (e) {
return null;
}
}
/* ---------- game logic ---------- */
function completedLines() {
return LINES.filter(function (line) {
return line.every(function (i) { return state.checked[i]; });
});
}
function checkedCount() {
var n = 0;
for (var i = 0; i < SIZE; i++) if (state.checked[i]) n++;
return n;
}
function subtitleFor() {
if (state.mode === 'A') return PRESETS.A.subtitle;
if (state.mode === 'B') return PRESETS.B.subtitle;
return '';
}
function buildBoard() {
els.board.textContent = '';
cells = [];
for (var i = 0; i < SIZE; i++) {
(function (idx) {
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'cell';
btn.setAttribute('aria-pressed', 'false');
var txt = document.createElement('span');
txt.className = 'txt';
var mark = document.createElement('span');
mark.className = 'mark';
mark.setAttribute('aria-hidden', 'true');
mark.textContent = '✓';
btn.appendChild(txt);
btn.appendChild(mark);
btn.addEventListener('click', function () { toggleCell(idx); });
els.board.appendChild(btn);
cells.push({ btn: btn, txt: txt });
})(i);
}
}
function updateBoard() {
+ hideExport();
var lines = completedLines();
var inLine = {};
lines.forEach(function (l) { l.forEach(function (i) { inLine[i] = true; }); });
for (var i = 0; i < SIZE; i++) {
var c = cells[i];
var on = !!state.checked[i];
var text = state.items[i];
var r = Math.floor(i / COLS) + 1;
var col = (i % COLS) + 1;
if (c.txt.textContent !== text) c.txt.textContent = text;
c.btn.setAttribute('aria-pressed', on ? 'true' : 'false');
c.btn.setAttribute(
'aria-label',
'第' + r + '行第' + col + '列:' + text + ',' + (on ? '已勾选' : '未勾选') + (inLine[i] ? ',在连线上' : '')
);
c.btn.classList.toggle('line', !!inLine[i]);
}
els.statusText.textContent = '已勾 ' + checkedCount() + ' / ' + SIZE + ' 格 · 连线 ' + lines.length + ' 条';
els.bingoBadge.hidden = lines.length === 0;
return lines.length;
}
function render() {
els.title.textContent = state.title;
var sub = subtitleFor();
els.subtitle.textContent = sub;
els.subtitle.hidden = !sub;
els.customOption.disabled = state.mode !== 'custom';
els.preset.value = state.mode;
updateBoard();
}
function setNote(msg) {
els.note.textContent = msg || '';
if (noteTimer) clearTimeout(noteTimer);
if (msg) {
noteTimer = setTimeout(function () { els.note.textContent = ''; }, 6000);
}
}
function celebrate() {
if (reduceMotion.matches) return;
try {
var colors = ['#d6246e', '#f5a623', '#2e9e4f', '#2f7de1', '#9b51e0', '#f2c94c'];
els.fx.textContent = '';
for (var i = 0; i < 26; i++) {
var p = document.createElement('i');
p.style.setProperty('--x', (Math.random() * 100).toFixed(1) + '%');
p.style.setProperty('--dx', (Math.random() * 80 - 40).toFixed(0) + 'px');
p.style.setProperty('--r', (Math.random() * 720 - 360).toFixed(0) + 'deg');
p.style.setProperty('--d', (Math.random() * 0.25).toFixed(2) + 's');
p.style.setProperty('--c', colors[i % colors.length]);
els.fx.appendChild(p);
}
if (fxTimer) clearTimeout(fxTimer);
fxTimer = setTimeout(function () { els.fx.textContent = ''; }, 2000);
els.bingoBadge.classList.remove('pulse');
void els.bingoBadge.offsetWidth;
els.bingoBadge.classList.add('pulse');
if (badgeTimer) clearTimeout(badgeTimer);
badgeTimer = setTimeout(function () { els.bingoBadge.classList.remove('pulse'); }, 1300);
} catch (e) { /* ignore */ }
}
function toggleCell(i) {
dirty = true;
var prev = completedLines().length;
state.checked[i] = !state.checked[i];
var now = updateBoard();
saveState();
if (prev === 0 && now > 0) celebrate();
}
/* ---------- buttons ---------- */
els.clearBtn.addEventListener('click', function () {
dirty = true;
state.checked = emptyChecked();
updateBoard();
saveState();
setNote('已清空勾选');
});
els.shuffleBtn.addEventListener('click', function () {
dirty = true;
var arr = state.items.slice();
for (var i = arr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
state.items = arr;
state.checked = emptyChecked();
updateBoard();
saveState();
setNote('已打乱格子位置并清空勾选');
});
els.preset.addEventListener('change', function () {
var v = els.preset.value;
if (v !== 'A' && v !== 'B') {
els.preset.value = state.mode;
return;
}
dirty = true;
state = presetState(v);
render();
saveState();
setNote('已切换题目,勾选已清空');
});
function buildResultText() {
var rows = [];
for (var r = 0; r < 5; r++) {
var line = '';
for (var c = 0; c < 5; c++) {
line += state.checked[r * 5 + c] ? '✅' : '⬜';
}
rows.push(line);
}
var summary = '已勾 ' + checkedCount() + '/' + SIZE + ',连线 ' + completedLines().length + ' 条';
return [state.title].concat(rows, [summary]).join('\n');
}
function showFallback(text) {
els.fallback.hidden = false;
els.fallbackText.value = text;
var ok = false;
try {
els.fallbackText.focus();
els.fallbackText.select();
els.fallbackText.setSelectionRange(0, text.length);
ok = document.execCommand && document.execCommand('copy');
} catch (e) {
ok = false;
}
if (ok) {
setNote('已复制,可直接粘贴到帖子里');
} else {
setNote('无法自动复制,文本已选中,请按 Ctrl/⌘+C 手动复制');
}
}
els.copyBtn.addEventListener('click', function () {
var text = buildResultText();
var hasApi = false;
try {
hasApi = !!(navigator.clipboard && typeof navigator.clipboard.writeText === 'function');
} catch (e) {
hasApi = false;
}
if (!hasApi) {
showFallback(text);
return;
}
var p;
try {
p = navigator.clipboard.writeText(text);
} catch (e) {
showFallback(text);
return;
}
Promise.resolve(p).then(function () {
els.fallback.hidden = true;
setNote('已复制,可直接粘贴到帖子里');
}, function () {
showFallback(text);
});
});
/* ---------- custom panel ---------- */
function charLen(s) {
return Array.from(s).length;
}
els.applyBtn.addEventListener('click', function () {
els.customError.textContent = '';
var items = els.customText.value.split(/\r?\n/).map(function (s) { return s.trim(); }).filter(function (s) { return s.length > 0; });
if (items.length !== SIZE) {
els.customError.textContent = '目前 ' + items.length + ' 项,需要 ' + SIZE + ' 项';
return;
}
for (var i = 0; i < items.length; i++) {
var n = charLen(items[i]);
if (n > 40) {
els.customError.textContent = '第 ' + (i + 1) + ' 项有 ' + n + ' 字,不能超过 40 字';
return;
}
}
var title = els.customTitle.value.trim();
if (!title) title = '自定义 Bingo';
dirty = true;
state = {
mode: 'custom',
title: title,
items: items,
checked: emptyChecked()
};
render();
saveState();
setNote('已套用自定义题目,勾选已清空');
});
els.fillBtn.addEventListener('click', function () {
els.customText.value = state.items.join('\n');
els.customTitle.value = state.title;
els.customError.textContent = '';
});
+ /* ---------- export image ---------- */
+
+ var exportUrl = null;
+ var exportBlob = null;
+ var exportCanvas = null;
+ var exportName = 'bingo.png';
+
+ function revokeExportUrl() {
+ if (exportUrl) {
+ try { URL.revokeObjectURL(exportUrl); } catch (e) { /* ignore */ }
+ exportUrl = null;
+ }
+ }
+
+ function hideExport() {
+ if (!els.exportPanel || els.exportPanel.hidden) return;
+ els.exportPanel.hidden = true;
+ els.exportImg.removeAttribute('src');
+ revokeExportUrl();
+ exportBlob = null;
+ exportCanvas = null;
+ }
+
+ function roundRect(ctx, x, y, w, h, r) {
+ r = Math.max(0, Math.min(r, w / 2, h / 2));
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.lineTo(x + w - r, y);
+ ctx.arcTo(x + w, y, x + w, y + r, r);
+ ctx.lineTo(x + w, y + h - r);
+ ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
+ ctx.lineTo(x + r, y + h);
+ ctx.arcTo(x, y + h, x, y + h - r, r);
+ ctx.lineTo(x, y + r);
+ ctx.arcTo(x, y, x + r, y, r);
+ ctx.closePath();
+ }
+
+ function wrapText(ctx, text, maxWidth) {
+ var chars = Array.from(String(text || ''));
+ var out = [];
+ var line = '';
+ for (var i = 0; i < chars.length; i++) {
+ var ch = chars[i];
+ if (ch === '\n') {
+ out.push(line);
+ line = '';
+ continue;
+ }
+ var test = line + ch;
+ if (line && ctx.measureText(test).width > maxWidth) {
+ out.push(line.replace(/\s+$/, ''));
+ line = /\s/.test(ch) ? '' : ch;
+ } else {
+ line = test;
+ }
+ }
+ out.push(line);
+ return out;
+ }
+
+ function fitCellText(ctx, text, family, boxW, boxH) {
+ var size = 26;
+ var lines = [];
+ for (; size >= 16; size -= 2) {
+ ctx.font = '600 ' + size + 'px ' + family;
+ lines = wrapText(ctx, text, boxW);
+ if (lines.length * size * 1.25 <= boxH) break;
+ }
+ if (size < 16) {
+ size = 16;
+ ctx.font = '600 16px ' + family;
+ lines = wrapText(ctx, text, boxW);
+ }
+ return { size: size, lines: lines };
+ }
+
+ function drawResultCanvas() {
+ var W = 1080, M = 40, GAP = 6, INNER = W - 2 * M;
+ var scale = Math.min(2, window.devicePixelRatio || 1);
+ var SERIF = '"Songti SC","Noto Serif CJK SC","SimSun",serif';
+ var SANS = 'system-ui,"PingFang SC","Microsoft YaHei",sans-serif';
+ var SCRIPT = '"Segoe Script","Bradley Hand","Marker Felt","Comic Sans MS",cursive';
+
+ var canvas = document.createElement('canvas');
+ canvas.width = W;
+ canvas.height = 100;
+ var ctx = canvas.getContext('2d');
+ if (!ctx) throw new Error('canvas unsupported');
+
+ var lines = completedLines();
+ var n = checkedCount();
+ var inLine = {};
+ lines.forEach(function (l) { l.forEach(function (i) { inLine[i] = true; }); });
+
+ var showPlayer = !!(els.player && !els.player.hidden && els.player.textContent);
+
+ var tSize = 64, tLines;
+ for (;;) {
+ ctx.font = '900 ' + tSize + 'px ' + SERIF;
+ tLines = wrapText(ctx, state.title, INNER);
+ if (tLines.length <= 1 || tSize <= 36) break;
+ tSize -= 4;
+ }
+ var tLH = Math.round(tSize * 1.2);
+
+ var sub = subtitleFor();
+ var sLines = [];
+ if (sub) {
+ ctx.font = '700 26px ' + SANS;
+ sLines = wrapText(ctx, sub, INNER);
+ }
+
+ var cell = (INNER - GAP * 4) / 5;
+ var y = M;
+ var playerY = 0, titleY, subY = 0, badgeY = 0, boardY, sumY, noteY;
+ if (showPlayer) { playerY = y; y += 34; }
+ titleY = y;
+ y += tLines.length * tLH;
+ if (sLines.length) { y += 10; subY = y; y += sLines.length * 36; }
+ if (lines.length) { y += 18; badgeY = y; y += 56 + 14; }
+ y += 20;
+ boardY = y;
+ y += cell * 5 + GAP * 4;
+ y += 36;
+ sumY = y;
+ y += 44;
+ noteY = y;
+ y += 28;
+ var H = Math.ceil(y + M);
+
+ canvas.width = Math.round(W * scale);
+ canvas.height = Math.round(H * scale);
+ ctx = canvas.getContext('2d');
+ ctx.scale(scale, scale);
+
+ ctx.fillStyle = '#fffdf8';
+ ctx.fillRect(0, 0, W, H);
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'top';
+
+ if (showPlayer) {
+ ctx.font = '600 22px ' + SANS;
+ ctx.fillStyle = '#555555';
+ ctx.fillText(els.player.textContent, W / 2, playerY);
+ }
+
+ ctx.font = '900 ' + tSize + 'px ' + SERIF;
+ ctx.fillStyle = '#111111';
+ var i;
+ for (i = 0; i < tLines.length; i++) {
+ ctx.fillText(tLines[i], W / 2, titleY + i * tLH);
+ }
+
+ if (sLines.length) {
+ ctx.font = '700 26px ' + SANS;
+ ctx.fillStyle = '#555555';
+ for (i = 0; i < sLines.length; i++) {
+ ctx.fillText(sLines[i], W / 2, subY + i * 36);
+ }
+ }
+
+ if (lines.length) {
+ var label = 'Bingo! ×' + lines.length;
+ ctx.font = '900 32px ' + SANS;
+ var bw = ctx.measureText(label).width + 60;
+ ctx.save();
+ ctx.translate(W / 2, badgeY + 28);
+ ctx.rotate(-4 * Math.PI / 180);
+ roundRect(ctx, -bw / 2, -28, bw, 56, 28);
+ ctx.fillStyle = '#1f7a3a';
+ ctx.fill();
+ ctx.fillStyle = '#ffffff';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(label, 0, 2);
+ ctx.restore();
+ }
+
+ for (i = 0; i < SIZE; i++) {
+ var r = Math.floor(i / COLS);
+ var c = i % COLS;
+ var x = M + c * (cell + GAP);
+ var yy = boardY + r * (cell + GAP);
+ var on = !!state.checked[i];
+ var lw = inLine[i] ? 4 : 2;
+
+ roundRect(ctx, x + lw / 2, yy + lw / 2, cell - lw, cell - lw, 4);
+ ctx.fillStyle = inLine[i] ? '#e3f6e8' : '#ffffff';
+ ctx.fill();
+ ctx.lineWidth = lw;
+ ctx.strokeStyle = inLine[i] ? '#2e9e4f' : '#111111';
+ ctx.stroke();
+
+ var fit = fitCellText(ctx, state.items[i], SANS, cell - 16, cell - 16);
+ var lh = fit.size * 1.25;
+ ctx.font = '600 ' + fit.size + 'px ' + SANS;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillStyle = '#111111';
+ ctx.globalAlpha = on ? 0.7 : 1;
+ var startY = yy + cell / 2 - (fit.lines.length - 1) * lh / 2;
+ for (var k = 0; k < fit.lines.length; k++) {
+ ctx.fillText(fit.lines[k], x + cell / 2, startY + k * lh);
+ }
+ ctx.globalAlpha = 1;
+
+ if (on) {
+ ctx.save();
+ ctx.translate(x + cell / 2, yy + cell / 2);
+ ctx.rotate(-12 * Math.PI / 180);
+ ctx.font = '900 ' + Math.round(cell * 0.75) + 'px ' + SCRIPT;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.lineJoin = 'round';
+ ctx.lineWidth = 3;
+ ctx.strokeStyle = '#ffffff';
+ ctx.strokeText('✓', 0, 0);
+ ctx.fillStyle = '#d6246e';
+ ctx.fillText('✓', 0, 0);
+ ctx.restore();
+ }
+
+ if (inLine[i]) {
+ ctx.font = '700 22px ' + SANS;
+ ctx.textAlign = 'left';
+ ctx.textBaseline = 'top';
+ ctx.fillStyle = '#2e9e4f';
+ ctx.fillText('✦', x + 8, yy + 6);
+ }
+ }
+
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'top';
+ ctx.font = '700 30px ' + SANS;
+ ctx.fillStyle = '#111111';
+ ctx.fillText('已勾 ' + n + ' / ' + SIZE + ' 格 · 连线 ' + lines.length + ' 条', W / 2, sumY);
+ ctx.font = '500 20px ' + SANS;
+ ctx.fillStyle = '#555555';
+ ctx.fillText('仅供娱乐连线,不能用于判断任何健康状况。', W / 2, noteY);
+
+ return canvas;
+ }
+
+ function exportFileName() {
+ var d = new Date();
+ function p(v) { return (v < 10 ? '0' : '') + v; }
+ return 'bingo-' + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) +
+ '-' + p(d.getHours()) + p(d.getMinutes()) + '.png';
+ }
+
+ function canCopyImage() {
+ try {
+ return !!(navigator.clipboard && typeof navigator.clipboard.write === 'function' &&
+ typeof window.ClipboardItem !== 'undefined');
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function triggerDownload() {
+ try {
+ var href = exportUrl || els.exportImg.getAttribute('src');
+ if (!href) return;
+ var a = document.createElement('a');
+ a.href = href;
+ a.download = exportName;
+ a.rel = 'noopener';
+ a.style.display = 'none';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ } catch (e) { /* silent: preview image is the fallback */ }
+ }
+
+ function showExport(src) {
+ els.exportImg.src = src;
+ els.exportPanel.hidden = false;
+ els.copyImgBtn.hidden = !canCopyImage();
+ try {
+ els.exportPanel.scrollIntoView({ block: 'nearest', behavior: reduceMotion.matches ? 'auto' : 'smooth' });
+ } catch (e) { /* ignore */ }
+ triggerDownload();
+ setNote('图片已生成');
+ }
+
+ function exportFailed() {
+ setNote('导出失败,请改用「复制结果」');
+ }
+
+ function doExport() {
+ withTimeout(document.fonts && document.fonts.ready, 600).then(function () {
+ try {
+ var canvas = drawResultCanvas();
+ revokeExportUrl();
+ exportBlob = null;
+ exportCanvas = canvas;
+ exportName = exportFileName();
+ if (typeof canvas.toBlob === 'function') {
+ canvas.toBlob(function (blob) {
+ try {
+ if (blob) {
+ exportBlob = blob;
+ exportUrl = URL.createObjectURL(blob);
+ showExport(exportUrl);
+ } else {
+ showExport(canvas.toDataURL('image/png'));
+ }
+ } catch (e) {
+ exportFailed();
+ }
+ }, 'image/png');
+ } else {
+ showExport(canvas.toDataURL('image/png'));
+ }
+ } catch (e) {
+ exportFailed();
+ }
+ });
+ }
+
+ function getExportBlob(cb) {
+ if (exportBlob) { cb(exportBlob); return; }
+ if (exportCanvas && typeof exportCanvas.toBlob === 'function') {
+ exportCanvas.toBlob(function (b) { cb(b); }, 'image/png');
+ } else {
+ cb(null);
+ }
+ }
+
+ els.exportBtn.addEventListener('click', doExport);
+
+ els.downloadBtn.addEventListener('click', function () {
+ triggerDownload();
+ setNote('已尝试下载,如无反应请长按/右键保存图片');
+ });
+
+ els.copyImgBtn.addEventListener('click', function () {
+ function fail() { setNote('当前环境不能直接复制图片,请长按/右键保存'); }
+ try {
+ getExportBlob(function (blob) {
+ if (!blob) { fail(); return; }
+ try {
+ Promise.resolve(
+ navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
+ ).then(function () {
+ setNote('图片已复制');
+ }, fail);
+ } catch (e) {
+ fail();
+ }
+ });
+ } catch (e) {
+ fail();
+ }
+ });
+
+ els.closeExportBtn.addEventListener('click', function () {
+ hideExport();
+ setNote('');
+ try { els.exportBtn.focus(); } catch (e) { /* ignore */ }
+ });
+
/* ---------- init ---------- */
buildBoard();
render();
(function loadUser() {
var ready;
try {
ready = window.discourseArtifactReady;
} catch (e) {
ready = null;
}
withTimeout(ready, 2500).then(function (info) {
if (info && info.username) {
els.player.textContent = '玩家:' + info.username;
els.player.hidden = false;
}
});
})();
(function loadSaved() {
storageGet(STORE_KEY).then(function (raw) {
if (!raw || dirty) return;
var s = sanitize(raw);
if (!s) return;
state = s;
render();
if (state.mode === 'custom') {
els.customTitle.value = state.title;
els.customText.value = state.items.join('\n');
}
}).catch(function () { /* silent */ });
})();
})();