AI制作的图编辑器

· · 科技·工程

AI制作的图编辑器

前言

2026-11-16 这一天, Graph Editor 的访问界面暂时变成了滚木(现在已经恢复正常),所以我使用 deepseek 用 html5 语言生成了具有该网站全部功能甚至更多功能的网页,希望能给大家带来一些帮助(画个简单的流程图也没有太大问题)。

功能介绍

操作模式

  1. 拖动模式:按住节点进行拖动,点击空白处添加节点。
  2. 删点模式:点击节点进行删除。
  3. 加边模式:依次点击起点和终点进行加边。
  4. 删边模式:点击边进行删除。

    显示调整

  5. 全局设置:点击“设置”按钮,可对节点大小、地图大小、边在力模式下的默认长度进行调整。点击“有(无)向图”可切换有向图 / 无向图。
  6. 力导向:点击“力导向”按钮进入力模式,各个节点会互相受到斥力的作用,被边连接的点会受到互相的引力作用。拖动模式下点击节点,节点会被锁定(不受力的作用,只能被拖动)。
  7. 节点外观:右键可进行重命名,更改颜色,更改形状(包括圆形、圆角矩形、圆角菱形)
  8. 节点名称:“0起始”“1起始”按钮可调整纯数字名称从 0 或 1 开始命名。“自定义”按钮可以使你能使用中文、英文、数字、全半角标点混合命名节点,并且引入转义符 \,\n 指名称内换行,\\ 表示正常反斜杠(主要是为了流程图)。
  9. 白天模式和黑夜模式。

    输入栏

  10. 按 u v (w) 格式输入(w 这一项选填),表示一条从 u 指向 v(或连接 u 和 v)的(边权为 w)边。
  11. 单独输入一个数字或不含空格的字符串(支持上文命名中提到的转义符 \)表示创建一个节点。

    打开方式

    创建一个文本文档,把代码复制进去并保存,把后缀改为 .html,并用浏览器打开。

    源代码

    :::info[源代码过长,进行收缩]

    
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <title>图编辑器 · CS Academy 风格</title>
    <style>

toolbar {

display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
padding: 6px 10px; background: #2a2a33; border-bottom: 1px solid #3a3a45;
font-size: 12px; z-index: 10;

} body.light #toolbar { background: #e8e8ec; border-bottom-color: #d0d0d8; }

toolbar button {

background: #3a3a45; color: #ddd; border: 1px solid #4a4a55;
padding: 4px 9px; border-radius: 5px; cursor: pointer; font-size: 12px;

} body.light #toolbar button { background: #fff; color: #333; border-color: #c0c0c8; }

toolbar button:hover { background: #4a4a55; }

body.light #toolbar button:hover { background: #f0f0f5; }

toolbar button.active { background: #4a7cff; border-color: #4a7cff; color: #fff; }

toolbar .group { display: flex; gap: 2px; margin-right: 8px; }

toolbar .group button { border-radius: 0; }

toolbar .group button:first-child { border-radius: 5px 0 0 5px; }

toolbar .group button:last-child { border-radius: 0 5px 5px 0; }

toolbar .sep { width: 1px; height: 20px; background: #4a4a55; margin: 0 6px; }

body.light #toolbar .sep { background: #c0c0c8; }

toolbar .hint { color: #888; font-size: 11px; max-width: 480px; }

main { flex: 1; display: flex; min-height: 0; }

sidebar {

width: 270px; display: flex; flex-direction: column;
background: #25252d; border-right: 1px solid #3a3a45;

} body.light #sidebar { background: #ececf0; border-right-color: #d0d0d8; }

sidebar .title {

padding: 8px 12px; font-size: 11px; color: #999;
border-bottom: 1px solid #33333d;

} body.light #sidebar .title { color: #666; border-bottom-color: #d0d0d8; }

sidebar textarea {

flex: 1; resize: none; border: none; outline: none;
background: #1e1e24; color: #e0e0e0;
font-family: Consolas, monospace; font-size: 12.5px;
padding: 10px 12px; line-height: 1.6;

} body.light #sidebar textarea { background: #fff; color: #222; }

sidebar .footer {

padding: 8px 12px; font-size: 10.5px; color: #777;
border-top: 1px solid #33333d; line-height: 1.55;

} body.light #sidebar .footer { color: #666; border-top-color: #d0d0d8; }

canvas { flex: 1; display: block; cursor: default; }

settingsPanel {

position: fixed; top: 50px; right: 12px; width: 280px;
background: #2a2a33; border: 1px solid #4a4a55; border-radius: 8px;
padding: 14px; box-shadow: 0 8px 24px rgba(0,0,0,0.5); z-index: 100;
display: none;

} body.light #settingsPanel { background: #fff; border-color: #c0c0c8; box-shadow: 0 8px 24px rgba(0,0,0,0.15); }

settingsPanel.visible { display: block; }

settingsPanel h3 {

margin: 0 0 12px; font-size: 14px; color: #fff;
display: flex; justify-content: space-between; align-items: center;

} body.light #settingsPanel h3 { color: #222; }

settingsPanel h3 button {

background: none; border: none; color: #888; cursor: pointer; font-size: 16px;
padding: 0 4px;

}

settingsPanel h3 button:hover { color: #fff; }

body.light #settingsPanel h3 button:hover { color: #000; } .setting-row { margin-bottom: 12px; } .setting-row label { display: block; font-size: 12px; color: #aaa; margin-bottom: 4px; } body.light .setting-row label { color: #555; } .setting-row label span { color: #4a7cff; font-weight: 600; } .setting-row input[type="range"] { width: 100%; accent-color: #4a7cff; }

contextMenu {

position: fixed; z-index: 200;
background: #2a2a33; border: 1px solid #4a4a55; border-radius: 8px;
padding: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.5);
min-width: 180px; display: none;

} body.light #contextMenu { background: #fff; border-color: #c0c0c8; box-shadow: 0 8px 24px rgba(0,0,0,0.15); }

contextMenu.visible { display: block; }

.cm-title { font-size: 11px; color: #888; margin: 4px 0 6px; } body.light .cm-title { color: #666; } .cm-colors { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin-bottom: 8px; } .cm-color { width: 32px; height: 32px; border-radius: 6px; cursor: pointer; border: 2px solid transparent; transition: border-color 0.15s; } .cm-color:hover { border-color: rgba(150,150,150,0.6); } .cm-color.selected { border-color: #4a7cff; } .cm-shapes { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 8px; } .cm-shapes button { background: #3a3a45; color: #ddd; border: 1px solid #4a4a55; padding: 6px 4px; border-radius: 5px; cursor: pointer; font-size: 12px; } body.light .cm-shapes button { background: #f0f0f5; color: #333; border-color: #c0c0c8; } .cm-shapes button:hover { background: #4a4a55; } body.light .cm-shapes button:hover { background: #e0e0e8; } .cm-shapes button.selected { background: #4a7cff; border-color: #4a7cff; color: #fff; }

cmRename {

width: 100%; background: #3a3a45; color: #ddd; border: 1px solid #4a4a55;
padding: 7px 4px; border-radius: 5px; cursor: pointer; font-size: 12px;

} body.light #cmRename { background: #f0f0f5; color: #333; border-color: #c0c0c8; }

cmRename:hover { background: #4a7cff; border-color: #4a7cff; color: #fff; }

</style> </head> <body> <div id="toolbar"> <div class="group" id="modeGroup"> <button data-mode="drag" class="active">拖动</button> <button data-mode="addEdge">加边</button> <button data-mode="delEdge">删边</button> <button data-mode="delNode">删点</button> </div> <div class="group" id="indexGroup"> <button data-index="0">0 起始</button> <button data-index="1" class="active">1 起始</button> <button data-index="custom">自定义</button> </div> <div class="group" id="lockGroup"> <button id="lockAll">全部锁定</button> <button id="unlockAll">全部解锁</button> </div> <button id="toggleDirected">无向图</button> <button id="toggleForce">力导向</button> <button id="layoutTree">树形排列</button> <button id="centerView">回到中心</button> <button id="toggleTheme">白天模式</button> <button id="openSettings">设置</button> <button id="downloadPng">下载图片</button> <button id="clearAll">清空</button> <span class="sep"></span> <span class="hint" id="hint">拖动:拖节点 / Shift+拖=加边 / 点空白=加节点 / 单击节点=锁定 / 右键节点=样式或重命名 / 双击边=改权重</span> </div>

<div id="main"> <div id="sidebar"> <div class="title">边列表(每行:u v [w])</div> <textarea id="input" spellcheck="false" placeholder="示例: 1 2 3 2 3 5 起点 终点 10 北京 上海 1200 A\nB 2"></textarea> <div class="footer"> <b>索引模式</b>:0起始/1起始下节点名须为数字;自定义支持汉字。<br> 节点名中 <code>\n</code> 表示换行,<code>\</code> 表示字面反斜杠。<br> 空行忽略;自环暂不支持;平行边会合并为一条。 </div> </div> <canvas id="canvas"></canvas> </div>

<div id="settingsPanel"> <h3>设置 <button id="closeSettings">✕</button></h3> <div class="setting-row"> <label>节点大小 <span id="nodeSizeVal">32</span></label> <input type="range" id="nodeSizeRange" min="20" max="60" value="32" step="1"> </div> <div class="setting-row"> <label>边长度(力导向)<span id="edgeLenVal">180</span></label> <input type="range" id="edgeLenRange" min="80" max="400" value="180" step="10"> </div> <div class="setting-row"> <label>地图宽度 <span id="mapWVal">2000</span></label> <input type="range" id="mapWRange" min="500" max="5000" value="2000" step="100"> </div> <div class="setting-row"> <label>地图高度 <span id="mapHVal">1500</span></label> <input type="range" id="mapHRange" min="500" max="4000" value="1500" step="100"> </div> </div>

<div id="contextMenu"> <div class="cm-title">颜色</div> <div class="cm-colors" id="cmColors"></div> <div class="cm-title">形状</div> <div class="cm-shapes" id="cmShapes"> <button data-shape="roundrect">方形</button> <button data-shape="circle">圆形</button> <button data-shape="diamond">菱形</button> </div> <div class="cm-title">操作</div> <button id="cmRename">✏️ 重命名</button> </div>

<script> (function() { 'use strict';

const STORAGE_KEY = 'graph-editor-cs-v5'; const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const input = document.getElementById('input'); const hint = document.getElementById('hint'); const toolbar = document.getElementById('toolbar'); const settingsPanel = document.getElementById('settingsPanel'); const contextMenu = document.getElementById('contextMenu'); const cmColors = document.getElementById('cmColors'); const cmShapes = document.getElementById('cmShapes');

const COLOR_PRESETS = { blue: { c1: '#5a8aff', c2: '#3a5fd0', label: '蓝' }, green: { c1: '#5ec93a', c2: '#3a8f2a', label: '绿' }, red: { c1: '#ff6b5a', c2: '#d03a2a', label: '红' }, orange: { c1: '#ffa45a', c2: '#d07a2a', label: '橙' }, yellow: { c1: '#ffd45a', c2: '#d0a02a', label: '黄' }, purple: { c1: '#b47aff', c2: '#8a4ad0', label: '紫' }, cyan: { c1: '#5ae0ff', c2: '#2aa8d0', label: '青' }, pink: { c1: '#ff8ac0', c2: '#d05a90', label: '粉' }, };

// 主题色板 const PALETTES = { dark: { bg: '#1e1e24', grid: '#2a2a33', mapBorder: '#3a3a60', edge: '#8a8aa0', weightBg: '#1e1e24', weightFg: '#ffcf5c', preview: '#ffcf5c', nodeShadow: 'rgba(0,0,0,0.4)', nodeBorder: 'rgba(255,255,255,0.5)', nodeFixed: '#ffcf5c', nodeHover: 'rgba(255,255,255,0.7)', nodeText: '#fff', warn: 'rgba(255,200,80,0.7)', specialStart: ['#ffd97a','#e0a83a'], specialTo: ['#a6ff7a','#5ec93a'], }, light: { bg: '#f5f5f7', grid: '#e0e0e5', mapBorder: '#a0a0d0', edge: '#606070', weightBg: '#f5f5f7', weightFg: '#b07800', preview: '#b07800', nodeShadow: 'rgba(0,0,0,0.15)', nodeBorder: 'rgba(0,0,0,0.25)', nodeFixed: '#b07800', nodeHover: 'rgba(0,0,0,0.55)', nodeText: '#fff', warn: 'rgba(160,110,0,0.8)', specialStart: ['#ffd97a','#e0a83a'], specialTo: ['#a6ff7a','#5ec93a'], } };

const state = { inputText: '', positions: {}, fixed: {}, nodeStyles: {}, settings: { nodeSize: 32, edgeLength: 180, mapWidth: 2000, mapHeight: 1500 }, theme: 'dark', directed: false, indexMode: 1, mode: 'drag', edges: [], nodeNames: [], dragName: null, dragOffset: {x:0,y:0}, dragStartScreen: null, dragMoved: false, edgeStart: null, mouse: {x:0,y:0}, hover: null, view: {x: 0, y: 0, scale: 1}, panning: false, panStart: {x:0,y:0}, viewStart: {x:0,y:0}, blankClickStart: null, shiftDrag: null, shiftHover: null, forceOn: false, velocities: {}, forceTimer: null, contextNodeName: null, _viewInitialized: false, };

function P() { return PALETTES[state.theme] || PALETTES.dark; }

// ---------- 持久化 ---------- function load() { state._viewInitialized = false; try { const raw = localStorage.getItem(STORAGE_KEY); if (!raw) return; const d = JSON.parse(raw); state.inputText = d.inputText || ''; state.positions = d.positions || {}; state.fixed = d.fixed || {}; state.nodeStyles = d.nodeStyles || {}; if (d.settings) Object.assign(state.settings, d.settings); state.theme = d.theme || 'dark'; state.directed = !!d.directed; state.indexMode = d.indexMode !== undefined ? d.indexMode : 1; if (d.view) { state.view = d.view; state._viewInitialized = true; } } catch(e){} } function save() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ inputText: state.inputText, positions: state.positions, fixed: state.fixed, nodeStyles: state.nodeStyles, settings: state.settings, theme: state.theme, directed: state.directed, indexMode: state.indexMode, view: state.view, })); } catch(e){} }

function applyTheme() { document.body.classList.toggle('light', state.theme === 'light'); const btn = document.getElementById('toggleTheme'); btn.textContent = state.theme === 'light' ? '夜间模式' : '白天模式'; }

// ---------- 节点样式 ---------- function getNodeStyle(name) { const st = state.nodeStyles[name] || {}; return { colorKey: st.color || 'blue', shape: st.shape || 'roundrect' }; } function getNodeColorPair(name) { return COLOR_PRESETS[getNodeStyle(name).colorKey] || COLOR_PRESETS.blue; }

// ---------- 文字解析 ---------- function splitLabel(name) { const lines = []; let cur = ''; let i = 0; while (i < name.length) { if (name[i] === '\' && i + 1 < name.length) { const next = name[i + 1]; if (next === '\') { cur += '\'; i += 2; continue; } if (next === 'n') { lines.push(cur); cur = ''; i += 2; continue; } cur += '\'; i += 1; continue; } cur += name[i]; i += 1; } lines.push(cur); return lines; }

function measureNodeSize(name) { const scale = state.settings.nodeSize / 32; const fontSize = Math.round(14 scale); ctx.font = ${fontSize}px system-ui, "Microsoft YaHei", sans-serif; const lines = splitLabel(name); const lineHeight = Math.round(fontSize 1.3); let maxTw = 0; for (const line of lines) maxTw = Math.max(maxTw, ctx.measureText(line).width); const pad = state.settings.nodeSize 0.7; const vPad = state.settings.nodeSize 0.3; let w = Math.max(state.settings.nodeSize 1.4, maxTw + pad); let h = Math.max(state.settings.nodeSize, lines.length lineHeight + vPad * 2); if (getNodeStyle(name).shape === 'circle') { const d = Math.max(w, h); w = d; h = d; } return { w, h }; }

// ---------- 索引模式转换 ---------- function convertInputIndex(oldMode, newMode) { if (oldMode === newMode) return; if (oldMode === 'custom' || newMode === 'custom') return; const offset = (newMode === 1 ? 1 : 0) - (oldMode === 1 ? 1 : 0); if (offset === 0) return; const lines = input.value.split('\n'); const newLines = lines.map(line => { const trimmed = line.trim(); if (!trimmed) return line; const parts = trimmed.split(/[\s,,]+/).filter(Boolean); const newParts = parts.map((p, i) => { if (i === 0 || i === 1) { if (/^-?\d+$/.test(p)) return String(parseInt(p) + offset); } return p; }); return newParts.join(' '); }); input.value = newLines.join('\n'); }

// ---------- 边界限制 ---------- function clampNodePosition(name) { const p = state.positions[name]; if (!p) return; const b = nodeBox(name); if (!b) return; const hw = Math.max(0, state.settings.mapWidth / 2 - b.w / 2); const hh = Math.max(0, state.settings.mapHeight / 2 - b.h / 2); const nx = Math.max(-hw, Math.min(hw, p.x)); const ny = Math.max(-hh, Math.min(hh, p.y)); if (nx !== p.x && state.velocities[name]) state.velocities[name].x = 0; if (ny !== p.y && state.velocities[name]) state.velocities[name].y = 0; p.x = nx; p.y = ny; } function clampAllNodes() { for (const n of state.nodeNames) clampNodePosition(n); } function clampView() { const W = canvas.clientWidth, H = canvas.clientHeight; const s = state.view.scale; const mw = state.settings.mapWidth s; const mh = state.settings.mapHeight s; if (mw >= W) state.view.x = Math.max(W - mw/2, Math.min(mw/2, state.view.x)); else state.view.x = W / 2; if (mh >= H) state.view.y = Math.max(H - mh/2, Math.min(mh/2, state.view.y)); else state.view.y = H / 2; }

// ---------- 解析输入 ---------- function parseInput() { state.inputText = input.value; const lines = input.value.split('\n'); const edges = []; const names = new Set(); for (let i = 0; i < lines.length; i++) { const raw = lines[i].trim(); if (!raw) continue; const parts = raw.split(/[\s,,]+/).filter(Boolean); if (parts.length === 1) { names.add(parts[0]); continue; } if (parts.length < 2) continue; const u = parts[0], v = parts[1]; if (u === v) continue; const w = parts.length >= 3 ? parts[2] : ''; edges.push({u, v, w, lineIndex: i}); names.add(u); names.add(v); } const list = Array.from(names); const need = list.filter(n => !state.positions[n]); if (need.length > 0) { const cxScreen = (canvas.clientWidth||600)/2; const cyScreen = (canvas.clientHeight||400)/2; const centerWorld = screenToWorld(cxScreen, cyScreen); const R = 120; const base = Object.keys(state.positions).length; need.forEach((n, idx) => { const total = Math.max(base + need.length, 6); const angle = (2Math.PI(base+idx))/total - Math.PI/2; state.positions[n] = { x: centerWorld.x + Math.cos(angle) R, y: centerWorld.y + Math.sin(angle) R, }; if (state.fixed[n] === undefined) state.fixed[n] = false; if (!state.velocities[n]) state.velocities[n] = {x:0, y:0}; }); } for (const n of list) if (!state.velocities[n]) state.velocities[n] = {x:0, y:0}; for (const n of Object.keys(state.positions)) { if (!names.has(n)) { delete state.positions[n]; delete state.fixed[n]; delete state.velocities[n]; delete state.nodeStyles[n]; } } state.edges = edges; state.nodeNames = list; clampAllNodes(); save(); }

// ---------- 视图变换 ---------- function screenToWorld(px, py) { const v = state.view; return {x: (px - v.x)/v.scale, y: (py - v.y)/v.scale}; } function worldToScreen(wx, wy) { const v = state.view; return {x: wxv.scale + v.x, y: wyv.scale + v.y}; }

function resize() { const dpr = window.devicePixelRatio || 1; const w = canvas.clientWidth, h = canvas.clientHeight; canvas.width = w dpr; canvas.height = h dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); if (!state._viewInitialized) { state._viewInitialized = true; state.view.scale = 1; state.view.x = w/2; state.view.y = h/2; } clampView(); draw(); }

// ---------- 节点几何 ---------- function nodeBox(name) { const pos = state.positions[name]; if (!pos) return null; const { w, h } = measureNodeSize(name); return { x: pos.x, y: pos.y, w, h, left: pos.x - w/2, top: pos.y - h/2, right: pos.x + w/2, bottom: pos.y + h/2, }; } function pointInNode(name, wx, wy) { const b = nodeBox(name); if (!b) return false; const shape = getNodeStyle(name).shape; const a = b.w/2, c = b.h/2; const dx = wx - b.x, dy = wy - b.y; if (shape === 'circle') return dxdx + dydy <= aa; if (shape === 'diamond') return Math.abs(dx)/a + Math.abs(dy)/c <= 1; return wx >= b.left && wx <= b.right && wy >= b.top && wy <= b.bottom; } function shapeIntersect(shape, b, dirx, diry) { const a = b.w/2, c = b.h/2; if (shape === 'circle') { const len = Math.hypot(dirx, diry) || 1; const t = a / len; return {x: b.x + dirxt, y: b.y + diryt}; } if (shape === 'diamond') { const t = 1 / (Math.abs(dirx)/a + Math.abs(diry)/c); return {x: b.x + dirxt, y: b.y + diryt}; } const tx = dirx !== 0 ? a/Math.abs(dirx) : Infinity; const ty = diry !== 0 ? c/Math.abs(diry) : Infinity; const t = Math.min(tx, ty); return {x: b.x + dirxt, y: b.y + diryt}; } function edgeEndpoints(u, v) { const bu = nodeBox(u), bv = nodeBox(v); if (!bu || !bv) return null; const dx = bv.x - bu.x, dy = bv.y - bu.y; const len = Math.hypot(dx, dy) || 1; const ux = dx/len, uy = dy/len; return { p1: shapeIntersect(getNodeStyle(u).shape, bu, ux, uy), p2: shapeIntersect(getNodeStyle(v).shape, bv, -ux, -uy), dx, dy, len, }; } function pointToSegment(px, py, x1, y1, x2, y2) { const dx = x2-x1, dy = y2-y1; const len2 = dxdx + dydy; if (len2 === 0) return Math.hypot(px-x1, py-y1); let t = ((px-x1)dx + (py-y1)dy)/len2; t = Math.max(0, Math.min(1, t)); return Math.hypot(px-(x1+tdx), py-(y1+t*dy)); }

// ---------- 形状绘制 ---------- function roundRectPath(x, y, w, h, r) { r = Math.max(0, Math.min(r, Math.min(w, h) / 2)); ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); } function diamondPath(cx, cy, w, h, r) { const a = w/2, b = h/2; const top = {x:cx,y:cy-b}, right = {x:cx+a,y:cy}, bottom = {x:cx,y:cy+b}, left = {x:cx-a,y:cy}; const edgeLen = Math.sqrt(aa + bb); const t = Math.min(0.4, r / edgeLen); const lerp = (p, q, s) => ({x: p.x + (q.x-p.x)s, y: p.y + (q.y-p.y)s}); const a1=lerp(top,right,t), a2=lerp(right,top,t); const b1=lerp(right,bottom,t), b2=lerp(bottom,right,t); const c1=lerp(bottom,left,t), c2=lerp(left,bottom,t); const d1=lerp(left,top,t), d2=lerp(top,left,t); ctx.beginPath(); ctx.moveTo(d2.x,d2.y); ctx.quadraticCurveTo(top.x,top.y,a1.x,a1.y); ctx.lineTo(a2.x,a2.y); ctx.quadraticCurveTo(right.x,right.y,b1.x,b1.y); ctx.lineTo(b2.x,b2.y); ctx.quadraticCurveTo(bottom.x,bottom.y,c1.x,c1.y); ctx.lineTo(c2.x,c2.y); ctx.quadraticCurveTo(left.x,left.y,d1.x,d1.y); ctx.lineTo(d2.x,d2.y); ctx.closePath(); } function nodeShapePath(b, shape, dx=0, dy=0) { const cx = b.x + dx, cy = b.y + dy; if (shape === 'circle') { ctx.beginPath(); ctx.arc(cx, cy, b.w/2, 0, Math.PI2); } else if (shape === 'diamond') { diamondPath(cx, cy, b.w, b.h, Math.min(b.w,b.h)0.15); } else { roundRectPath(cx-b.w/2, cy-b.h/2, b.w, b.h, Math.min(b.w,b.h)*0.25); } }

// ---------- 绘制 ---------- function draw() { const pal = P(); const W = canvas.clientWidth, H = canvas.clientHeight; ctx.fillStyle = pal.bg; ctx.fillRect(0, 0, W, H);

ctx.save();
const v = state.view;
ctx.translate(v.x, v.y);
ctx.scale(v.scale, v.scale);

const grid = 40;
ctx.strokeStyle = pal.grid;
ctx.lineWidth = 1 / v.scale;
const left = -v.x/v.scale, top = -v.y/v.scale;
const right = left + W/v.scale, bottom = top + H/v.scale;
for (let x = Math.floor(left/grid)*grid; x < right; x += grid) {
  ctx.beginPath(); ctx.moveTo(x, top); ctx.lineTo(x, bottom); ctx.stroke();
}
for (let y = Math.floor(top/grid)*grid; y < bottom; y += grid) {
  ctx.beginPath(); ctx.moveTo(left, y); ctx.lineTo(right, y); ctx.stroke();
}

const mw = state.settings.mapWidth, mh = state.settings.mapHeight;
ctx.save();
ctx.strokeStyle = pal.mapBorder;
ctx.lineWidth = 2 / v.scale;
ctx.setLineDash([10/v.scale, 6/v.scale]);
ctx.strokeRect(-mw/2, -mh/2, mw, mh);
ctx.restore();

for (const e of state.edges) {
  const ep = edgeEndpoints(e.u, e.v); if (!ep) continue;
  const {p1, p2, dx, dy} = ep;
  ctx.strokeStyle = pal.edge;
  ctx.lineWidth = 2 / v.scale;
  ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.stroke();
  if (state.directed) {
    const angle = Math.atan2(dy, dx);
    const ah = 12/v.scale, aw = 7/v.scale;
    const tipX = p2.x, tipY = p2.y;
    const lx = tipX - ah*Math.cos(angle) - aw*Math.sin(angle);
    const ly = tipY - ah*Math.sin(angle) + aw*Math.cos(angle);
    const rx = tipX - ah*Math.cos(angle) + aw*Math.sin(angle);
    const ry = tipY - ah*Math.sin(angle) - aw*Math.cos(angle);
    ctx.fillStyle = pal.edge;
    ctx.beginPath(); ctx.moveTo(tipX, tipY); ctx.lineTo(lx, ly); ctx.lineTo(rx, ry); ctx.closePath(); ctx.fill();
  }
  if (e.w !== '') {
    const mx = (p1.x+p2.x)/2, my = (p1.y+p2.y)/2;
    const text = String(e.w);
    const fs = 13/v.scale;
    ctx.font = `bold ${fs}px system-ui, "Microsoft YaHei", sans-serif`;
    const tw = ctx.measureText(text).width;
    const pad = 6/v.scale, bw = tw+pad*2, bh = 20/v.scale;
    ctx.fillStyle = pal.weightBg;
    roundRectPath(mx-bw/2, my-bh/2, bw, bh, 4/v.scale); ctx.fill();
    ctx.fillStyle = pal.weightFg;
    ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
    ctx.fillText(text, mx, my + 1/v.scale);
  }
}

if (state.shiftDrag) {
  const b = nodeBox(state.shiftDrag.from);
  if (b) {
    const mw2 = screenToWorld(state.mouse.x, state.mouse.y);
    ctx.strokeStyle = pal.preview;
    ctx.setLineDash([6/v.scale, 6/v.scale]);
    ctx.lineWidth = 2/v.scale;
    ctx.beginPath(); ctx.moveTo(b.x, b.y);
    if (state.shiftHover) { const tb = nodeBox(state.shiftHover); ctx.lineTo(tb.x, tb.y); }
    else ctx.lineTo(mw2.x, mw2.y);
    ctx.stroke(); ctx.setLineDash([]);
  }
}
if (state.mode === 'addEdge' && state.edgeStart) {
  const b = nodeBox(state.edgeStart);
  if (b) {
    const mw2 = screenToWorld(state.mouse.x, state.mouse.y);
    ctx.strokeStyle = pal.preview;
    ctx.setLineDash([6/v.scale, 6/v.scale]);
    ctx.lineWidth = 2/v.scale;
    ctx.beginPath(); ctx.moveTo(b.x, b.y); ctx.lineTo(mw2.x, mw2.y);
    ctx.stroke(); ctx.setLineDash([]);
  }
}

for (const name of state.nodeNames) {
  const b = nodeBox(name); if (!b) continue;
  const style = getNodeStyle(name);
  const isStart = state.mode === 'addEdge' && state.edgeStart === name;
  const isHover = state.hover === name;
  const isShiftFrom = state.shiftDrag && state.shiftDrag.from === name;
  const isShiftTo = state.shiftHover === name;
  const isFixed = state.fixed[name];

  nodeShapePath(b, style.shape, 2, 3);
  ctx.fillStyle = pal.nodeShadow; ctx.fill();

  let c1, c2;
  if (isStart || isShiftFrom) { [c1, c2] = pal.specialStart; }
  else if (isShiftTo)         { [c1, c2] = pal.specialTo; }
  else { const base = getNodeColorPair(name); c1 = base.c1; c2 = base.c2; }
  const g = ctx.createLinearGradient(0, b.top, 0, b.bottom);
  g.addColorStop(0, c1); g.addColorStop(1, c2);
  nodeShapePath(b, style.shape);
  ctx.fillStyle = g; ctx.fill();

  nodeShapePath(b, style.shape);
  ctx.strokeStyle = isFixed ? pal.nodeFixed : pal.nodeBorder;
  ctx.lineWidth = (isFixed ? 2.5 : 1.5) / v.scale;
  ctx.stroke();

  if (isHover) {
    nodeShapePath(b, style.shape);
    ctx.strokeStyle = pal.nodeHover;
    ctx.lineWidth = 4 / v.scale;
    ctx.stroke();
  }
  if (isFixed) {
    ctx.fillStyle = pal.nodeFixed;
    ctx.beginPath(); ctx.arc(b.right - 4/v.scale, b.top + 4/v.scale, 3.5/v.scale, 0, Math.PI*2); ctx.fill();
  }

  const scale = state.settings.nodeSize / 32;
  const fs = Math.round(14 * scale);
  const lineHeight = Math.round(fs * 1.3);
  const lines = splitLabel(name);
  const totalH = lines.length * lineHeight;
  ctx.fillStyle = pal.nodeText;
  ctx.font = `${fs}px system-ui, "Microsoft YaHei", sans-serif`;
  ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  for (let i = 0; i < lines.length; i++) {
    const ly = b.y - totalH/2 + lineHeight/2 + i*lineHeight;
    ctx.fillText(lines[i], b.x, ly);
  }
}

if (state.nodeNames.length > 60) {
  ctx.fillStyle = pal.warn;
  ctx.font = '12px system-ui, sans-serif';
  ctx.textAlign = 'right'; ctx.textBaseline = 'top';
  ctx.fillText(`节点数 ${state.nodeNames.length},建议 ≤ 60`, W/v.scale - 16/v.scale, 16/v.scale);
}
ctx.restore();

}

// ---------- 命中测试 ---------- function getScreenPos(e) { const rect = canvas.getBoundingClientRect(); return {x: e.clientX - rect.left, y: e.clientY - rect.top}; } function nodeAtScreen(px, py) { const w = screenToWorld(px, py); for (let i = state.nodeNames.length-1; i >= 0; i--) if (pointInNode(state.nodeNames[i], w.x, w.y)) return state.nodeNames[i]; return null; } function edgeAtScreen(px, py) { const w = screenToWorld(px, py); let best = null, bestDist = 8 / state.view.scale; for (const e of state.edges) { const ep = edgeEndpoints(e.u, e.v); if (!ep) continue; const d = pointToSegment(w.x, w.y, ep.p1.x, ep.p1.y, ep.p2.x, ep.p2.y); if (d < bestDist) { bestDist = d; best = e; } } return best; }

// ---------- 输入框操作 ---------- function appendLine(line) { let next = input.value; if (next.length > 0 && !next.endsWith('\n')) next += '\n'; next += line + '\n'; input.value = next; parseInput(); draw(); input.scrollTop = input.scrollHeight; } function removeEdgeFromInput(edge) { const lines = input.value.split('\n'); let removed = false; for (let i = 0; i < lines.length; i++) { const parts = lines[i].trim().split(/[\s,,]+/).filter(Boolean); if (parts.length >= 2 && parts[0] === edge.u && parts[1] === edge.v) { lines.splice(i, 1); removed = true; break; } } if (!removed) return; const nodeInLines = (name) => lines.some(line => { const parts = line.trim().split(/[\s,,]+/).filter(Boolean); if (parts.length === 0) return false; if (parts.length === 1) return parts[0] === name; return parts[0] === name || parts[1] === name; }); if (!nodeInLines(edge.u)) lines.push(edge.u); if (!nodeInLines(edge.v)) lines.push(edge.v); input.value = lines.join('\n'); parseInput(); draw(); } function removeNodeFromInput(name) { const kept = input.value.split('\n').filter(line => { const parts = line.trim().split(/[\s,,]+/).filter(Boolean); if (parts.length === 0) return true; if (parts.length === 1) return parts[0] !== name; return parts[0] !== name && parts[1] !== name; }); input.value = kept.join('\n'); delete state.positions[name]; delete state.fixed[name]; delete state.velocities[name]; delete state.nodeStyles[name]; parseInput(); draw(); }

// ---------- 重命名 ---------- function renameNode(oldName) { const newName = prompt('输入新名字(支持 \n 换行)', oldName); if (newName === null) return; const trimmed = newName.trim(); if (trimmed === '' || trimmed === oldName) return; if (state.nodeNames.includes(trimmed)) { alert('节点名已存在:' + trimmed); return; } const lines = input.value.split('\n'); const newLines = lines.map(line => { const parts = line.trim().split(/[\s,,]+/).filter(Boolean); if (parts.length === 0) return line; if (parts[0] === oldName) parts[0] = trimmed; if (parts.length >= 2 && parts[1] === oldName) parts[1] = trimmed; return parts.join(' '); }); input.value = newLines.join('\n'); if (state.positions[oldName]) { state.positions[trimmed] = state.positions[oldName]; delete state.positions[oldName]; } if (state.fixed[oldName] !== undefined) { state.fixed[trimmed] = state.fixed[oldName]; delete state.fixed[oldName]; } if (state.nodeStyles[oldName]) { state.nodeStyles[trimmed] = state.nodeStyles[oldName]; delete state.nodeStyles[oldName]; } if (state.velocities[oldName]) { state.velocities[trimmed] = state.velocities[oldName]; delete state.velocities[oldName]; } parseInput(); draw(); }

// ---------- 锁定 / 解锁 / 布局 ---------- function lockAll() { for (const n of state.nodeNames) state.fixed[n] = true; save(); draw(); } function unlockAll() { for (const n of state.nodeNames) state.fixed[n] = false; save(); draw(); } function centerView() { const W = canvas.clientWidth, H = canvas.clientHeight; state.view.scale = 1; state.view.x = W/2; state.view.y = H/2; clampView(); save(); draw(); } function layoutTree() { const names = state.nodeNames; if (names.length === 0) return; if (state.forceOn) stopForce(); const adj = {}, deg = {}; for (const n of names) { adj[n] = []; deg[n] = 0; } const seenPair = new Set(); for (const e of state.edges) { const k1 = ${e.u}\u0000${e.v}, k2 = ${e.v}\u0000${e.u}; if (state.directed) { if (!seenPair.has(k1)) { seenPair.add(k1); adj[e.u].push(e.v); deg[e.v]++; } } else { if (!seenPair.has(k1) && !seenPair.has(k2)) { seenPair.add(k1); adj[e.u].push(e.v); adj[e.v].push(e.u); deg[e.v]++; deg[e.u]++; } } } const levels = []; if (state.directed) { const rem = Object.assign({}, deg); const visited = new Set(); let cur = names.filter(n => deg[n] === 0); if (cur.length === 0) cur = [names[0]]; cur.forEach(n => visited.add(n)); while (cur.length > 0) { levels.push(cur.slice()); const next = []; for (const u of cur) for (const v of adj[u]) { rem[v]--; if (rem[v] <= 0 && !visited.has(v)) { visited.add(v); next.push(v); } } cur = next; } const rest = names.filter(n => !visited.has(n)); if (rest.length > 0) { let queue = [rest[0]]; visited.add(rest[0]); while (queue.length > 0) { levels.push(queue.slice()); const next = []; for (const u of queue) for (const v of adj[u]) if (!visited.has(v)) { visited.add(v); next.push(v); } queue = next; } } } else { const root = names.reduce((a, b) => (deg[a] >= deg[b] ? a : b)); const visited = new Set([root]); let cur = [root]; while (cur.length > 0) { levels.push(cur.slice()); const next = []; for (const u of cur) for (const v of adj[u]) if (!visited.has(v)) { visited.add(v); next.push(v); } cur = next; } const rest = names.filter(n => !visited.has(n)); if (rest.length > 0) levels.push(rest); } const centerW = screenToWorld(canvas.clientWidth/2, canvas.clientHeight/2); const scale = state.settings.nodeSize / 32; const nodeGap = state.settings.nodeSize 0.6; const minGap = state.settings.nodeSize 1.2 scale; const layerHeights = levels.map(level => { let mh = 0; for (const name of level) mh = Math.max(mh, measureNodeSize(name).h); return mh; }); const totalH = layerHeights.reduce((s, h) => s + h, 0) + minGap Math.max(0, levels.length - 1); let accY = centerW.y - totalH/2; levels.forEach((level, li) => { const rowH = layerHeights[li]; const y = accY + rowH/2; const widths = level.map(name => measureNodeSize(name).w); const totalW = widths.reduce((s, w) => s + w, 0) + (level.length - 1) * nodeGap; let curX = centerW.x - totalW/2; level.forEach((name, ni) => { state.positions[name] = { x: curX + widths[ni]/2, y }; curX += widths[ni] + nodeGap; }); accY += rowH + minGap; }); clampAllNodes(); save(); draw(); }

// ---------- 右键菜单 ---------- function showContextMenu(x, y, nodeName) { state.contextNodeName = nodeName; renderContextMenuColors(nodeName); renderContextMenuShapes(nodeName); document.getElementById('cmRename').onclick = () => { hideContextMenu(); renameNode(nodeName); }; contextMenu.classList.add('visible'); const rect = contextMenu.getBoundingClientRect(); let px = x, py = y; if (px + rect.width > window.innerWidth) px = window.innerWidth - rect.width - 8; if (py + rect.height > window.innerHeight) py = window.innerHeight - rect.height - 8; contextMenu.style.left = px + 'px'; contextMenu.style.top = py + 'px'; } function hideContextMenu() { contextMenu.classList.remove('visible'); state.contextNodeName = null; } function renderContextMenuColors(nodeName) { const st = getNodeStyle(nodeName); cmColors.innerHTML = ''; for (const key of Object.keys(COLOR_PRESETS)) { const p = COLOR_PRESETS[key]; const div = document.createElement('div'); div.className = 'cm-color' + (key === st.colorKey ? ' selected' : ''); div.style.background = linear-gradient(180deg, ${p.c1}, ${p.c2}); div.title = p.label; div.onclick = () => { if (!state.nodeStyles[nodeName]) state.nodeStyles[nodeName] = {}; state.nodeStyles[nodeName].color = key; clampNodePosition(nodeName); save(); draw(); hideContextMenu(); }; cmColors.appendChild(div); } } function renderContextMenuShapes(nodeName) { const st = getNodeStyle(nodeName); cmShapes.querySelectorAll('button').forEach(btn => { btn.classList.toggle('selected', btn.dataset.shape === st.shape); btn.onclick = () => { if (!state.nodeStyles[nodeName]) state.nodeStyles[nodeName] = {}; state.nodeStyles[nodeName].shape = btn.dataset.shape; clampNodePosition(nodeName); save(); draw(); hideContextMenu(); }; }); }

// ---------- 鼠标交互 ---------- canvas.addEventListener('mousedown', (e) => { if (e.button !== 0) return; hideContextMenu(); const p = getScreenPos(e); state.mouse = p;

if (e.shiftKey && state.mode === 'drag') {
  const n = nodeAtScreen(p.x, p.y);
  if (n) { state.shiftDrag = {from: n}; state.shiftHover = null; draw(); return; }
}
const hitNode = nodeAtScreen(p.x, p.y);
if (!hitNode && state.mode === 'drag') {
  state.panning = true;
  state.panStart = p;
  state.viewStart = {x: state.view.x, y: state.view.y};
  state.blankClickStart = p;
  canvas.style.cursor = 'grabbing';
  return;
}
if (state.mode === 'drag') {
  if (hitNode) {
    state.dragName = hitNode;
    const pos = state.positions[hitNode];
    const w = screenToWorld(p.x, p.y);
    state.dragOffset = {x: w.x - pos.x, y: w.y - pos.y};
    state.dragStartScreen = p; state.dragMoved = false;
    canvas.style.cursor = 'grabbing';
  }
} else if (state.mode === 'addEdge') {
  if (hitNode) {
    if (!state.edgeStart) state.edgeStart = hitNode;
    else if (state.edgeStart !== hitNode) {
      appendLine(`${state.edgeStart} ${hitNode}`);
      state.edgeStart = null;
    }
    draw();
  } else { state.edgeStart = null; draw(); }
} else if (state.mode === 'delEdge') {
  const ed = edgeAtScreen(p.x, p.y);
  if (ed) removeEdgeFromInput(ed);
} else if (state.mode === 'delNode') {
  if (hitNode) removeNodeFromInput(hitNode);
}

});

canvas.addEventListener('mousemove', (e) => { const p = getScreenPos(e); state.mouse = p; if (state.panning) { state.view.x = state.viewStart.x + (p.x - state.panStart.x); state.view.y = state.viewStart.y + (p.y - state.panStart.y); clampView(); draw(); return; } if (state.dragName) { const w = screenToWorld(p.x, p.y); const pos = state.positions[state.dragName]; pos.x = w.x - state.dragOffset.x; pos.y = w.y - state.dragOffset.y; clampNodePosition(state.dragName); if (!state.dragMoved) { const dx = p.x - state.dragStartScreen.x, dy = p.y - state.dragStartScreen.y; if (dxdx + dydy > 9) state.dragMoved = true; } draw(); return; } if (state.shiftDrag) { state.shiftHover = nodeAtScreen(p.x, p.y); if (state.shiftHover === state.shiftDrag.from) state.shiftHover = null; draw(); return; } let hover = null; if (state.mode !== 'delEdge') hover = nodeAtScreen(p.x, p.y); if (hover !== state.hover) { state.hover = hover; canvas.style.cursor = hover ? (state.mode === 'drag' ? 'grab' : 'pointer') : 'default'; draw(); } if (state.mode === 'addEdge' && state.edgeStart) draw(); });

canvas.addEventListener('mouseup', (e) => { const p = getScreenPos(e); if (state.shiftDrag) { const to = nodeAtScreen(p.x, p.y); if (to && to !== state.shiftDrag.from) appendLine(${state.shiftDrag.from} ${to}); state.shiftDrag = null; state.shiftHover = null; draw(); return; } if (state.panning) { const moved = Math.hypot(p.x - state.blankClickStart.x, p.y - state.blankClickStart.y); state.panning = false; canvas.style.cursor = 'default'; if (moved < 5 && state.mode === 'drag') { const w = screenToWorld(p.x, p.y); const name = nextFreeNodeName(); state.positions[name] = {x: w.x, y: w.y}; state.fixed[name] = false; state.velocities[name] = {x:0, y:0}; clampNodePosition(name); appendLine(name); state.positions[name] = {x: w.x, y: w.y}; state.fixed[name] = false; state.velocities[name] = {x:0, y:0}; draw(); } state.blankClickStart = null; return; } if (state.dragName) { const name = state.dragName; if (!state.dragMoved) state.fixed[name] = !state.fixed[name]; state.dragName = null; state.dragMoved = false; state.dragStartScreen = null; canvas.style.cursor = state.hover ? 'grab' : 'default'; save(); draw(); } });

canvas.addEventListener('mouseleave', () => { state.hover = null; if (state.dragName) { state.dragName = null; state.dragMoved = false; save(); } if (state.shiftDrag) { state.shiftDrag = null; state.shiftHover = null; } if (state.panning) { state.panning = false; state.blankClickStart = null; } draw(); });

canvas.addEventListener('contextmenu', (e) => { e.preventDefault(); const p = getScreenPos(e); const hitNode = nodeAtScreen(p.x, p.y); if (hitNode) showContextMenu(e.clientX, e.clientY, hitNode); else hideContextMenu(); }); document.addEventListener('mousedown', (e) => { if (!contextMenu.contains(e.target)) hideContextMenu(); });

canvas.addEventListener('dblclick', (e) => { const p = getScreenPos(e); const ed = edgeAtScreen(p.x, p.y); if (!ed) return; const cur = ed.w === '' ? '' : ed.w; const next = prompt('输入边权(留空则删除权重)', cur); if (next === null) return; const lines = input.value.split('\n'); const parts = lines[ed.lineIndex].trim().split(/[\s,,]+/).filter(Boolean); const head = parts.slice(0, 2).join(' '); lines[ed.lineIndex] = next === '' ? head : ${head} ${next}; input.value = lines.join('\n'); parseInput(); draw(); });

canvas.addEventListener('wheel', (e) => { e.preventDefault(); const p = getScreenPos(e); const worldBefore = screenToWorld(p.x, p.y); const factor = e.deltaY < 0 ? 1.12 : 1/1.12; const newScale = Math.max(0.1, Math.min(4, state.view.scale factor)); state.view.scale = newScale; const worldAfter = screenToWorld(p.x, p.y); state.view.x += (worldAfter.x - worldBefore.x) newScale; state.view.y += (worldAfter.y - worldBefore.y) * newScale; clampView(); save(); draw(); }, {passive: false});

// ---------- 力导向 ---------- function startForce() { if (state.forceTimer) return; state.forceOn = true; document.getElementById('toggleForce').classList.add('active'); for (const n of state.nodeNames) if (!state.velocities[n]) state.velocities[n] = {x:0, y:0}; state.forceTimer = setInterval(() => { stepForce(); draw(); }, 33); } function stopForce() { state.forceOn = false; if (state.forceTimer) { clearInterval(state.forceTimer); state.forceTimer = null; } document.getElementById('toggleForce').classList.remove('active'); } function stepForce() { const names = state.nodeNames; const k = 0.06; const rep = 9000 (state.settings.nodeSize/32) (state.settings.nodeSize/32); const damping = 0.82; const centerW = screenToWorld(canvas.clientWidth/2, canvas.clientHeight/2); for (const n of names) if (!state.velocities[n]) state.velocities[n] = {x:0, y:0}; for (let i = 0; i < names.length; i++) { for (let j = i+1; j < names.length; j++) { const a = names[i], b = names[j]; const pa = state.positions[a], pb = state.positions[b]; if (!pa || !pb) continue; let dx = pa.x - pb.x, dy = pa.y - pb.y; let d2 = dxdx + dydy; if (d2 < 1) d2 = 1; const d = Math.sqrt(d2); const f = rep / d2; const fx = f dx/d, fy = f dy/d; if (!state.fixed[a]) { state.velocities[a].x += fx; state.velocities[a].y += fy; } if (!state.fixed[b]) { state.velocities[b].x -= fx; state.velocities[b].y -= fy; } } } for (const e of state.edges) { const pa = state.positions[e.u], pb = state.positions[e.v]; if (!pa || !pb) continue; const dx = pb.x - pa.x, dy = pb.y - pa.y; const d = Math.hypot(dx, dy) || 1; const target = state.settings.edgeLength; const f = (d - target) k; const fx = f dx/d, fy = f dy/d; if (!state.fixed[e.u]) { state.velocities[e.u].x += fx; state.velocities[e.u].y += fy; } if (!state.fixed[e.v]) { state.velocities[e.v].x -= fx; state.velocities[e.v].y -= fy; } } for (const n of names) { if (state.fixed[n]) continue; const p = state.positions[n], v = state.velocities[n]; v.x += (centerW.x - p.x) 0.002; v.y += (centerW.y - p.y) 0.002; v.x = damping; v.y = damping; p.x += v.x 0.5; p.y += v.y * 0.5; clampNodePosition(n); } save(); }

function nextFreeNodeName() { if (state.indexMode === 'custom') { let i = 1; while (state.nodeNames.includes(节点${i})) i++; return 节点${i}; } let i = state.indexMode === 0 ? 0 : 1; while (state.nodeNames.includes(String(i))) i++; return String(i); }

function downloadPng() { const tmp = document.createElement('canvas'); tmp.width = canvas.width; tmp.height = canvas.height; const tctx = tmp.getContext('2d'); tctx.drawImage(canvas, 0, 0); const a = document.createElement('a'); a.download = '图编辑器.png'; a.href = tmp.toDataURL('image/png'); a.click(); }

// ---------- 设置面板 ---------- function updateSettingsUI() { document.getElementById('nodeSizeRange').value = state.settings.nodeSize; document.getElementById('nodeSizeVal').textContent = state.settings.nodeSize; document.getElementById('edgeLenRange').value = state.settings.edgeLength; document.getElementById('edgeLenVal').textContent = state.settings.edgeLength; document.getElementById('mapWRange').value = state.settings.mapWidth; document.getElementById('mapWVal').textContent = state.settings.mapWidth; document.getElementById('mapHRange').value = state.settings.mapHeight; document.getElementById('mapHVal').textContent = state.settings.mapHeight; } function bindSettings() { document.getElementById('nodeSizeRange').addEventListener('input', (e) => { state.settings.nodeSize = parseInt(e.target.value); document.getElementById('nodeSizeVal').textContent = state.settings.nodeSize; clampAllNodes(); save(); draw(); }); document.getElementById('edgeLenRange').addEventListener('input', (e) => { state.settings.edgeLength = parseInt(e.target.value); document.getElementById('edgeLenVal').textContent = state.settings.edgeLength; save(); draw(); }); document.getElementById('mapWRange').addEventListener('input', (e) => { state.settings.mapWidth = parseInt(e.target.value); document.getElementById('mapWVal').textContent = state.settings.mapWidth; clampAllNodes(); clampView(); save(); draw(); }); document.getElementById('mapHRange').addEventListener('input', (e) => { state.settings.mapHeight = parseInt(e.target.value); document.getElementById('mapHVal').textContent = state.settings.mapHeight; clampAllNodes(); clampView(); save(); draw(); }); document.getElementById('closeSettings').onclick = () => settingsPanel.classList.remove('visible'); }

// ---------- 工具栏 ---------- toolbar.addEventListener('click', (e) => { const btn = e.target.closest('button'); if (!btn) return;

if (btn.dataset.mode) {
  state.mode = btn.dataset.mode; state.edgeStart = null;
  document.querySelectorAll('#toolbar button[data-mode]').forEach(b => b.classList.toggle('active', b === btn));
  hint.textContent = {
    drag: '拖动:拖节点 / Shift+拖=加边 / 点空白=加节点 / 单击节点=锁定 / 右键节点=样式或重命名 / 双击边=改权重',
    addEdge: '加边模式:依次点击两个节点',
    delEdge: '删边模式:点击边删除',
    delNode: '删点模式:点击节点删除',
  }[state.mode];
  draw();
}
if (btn.dataset.index) {
  const mode = btn.dataset.index === 'custom' ? 'custom' : parseInt(btn.dataset.index);
  if (mode === state.indexMode) return;
  convertInputIndex(state.indexMode, mode);
  state.indexMode = mode;
  document.querySelectorAll('#toolbar button[data-index]').forEach(b => b.classList.toggle('active', b === btn));
  parseInput(); draw(); save();
}
if (btn.id === 'lockAll') lockAll();
if (btn.id === 'unlockAll') unlockAll();
if (btn.id === 'layoutTree') layoutTree();
if (btn.id === 'centerView') centerView();
if (btn.id === 'toggleDirected') {
  state.directed = !state.directed;
  btn.textContent = state.directed ? '有向图' : '无向图';
  save(); draw();
}
if (btn.id === 'toggleForce') { state.forceOn ? stopForce() : startForce(); }
if (btn.id === 'toggleTheme') {
  state.theme = state.theme === 'dark' ? 'light' : 'dark';
  applyTheme(); save(); draw();
}
if (btn.id === 'openSettings') { settingsPanel.classList.toggle('visible'); updateSettingsUI(); }
if (btn.id === 'downloadPng') downloadPng();
if (btn.id === 'clearAll') {
  if (confirm('确定清空所有节点和边?')) {
    input.value = '';
    state.positions = {}; state.fixed = {}; state.velocities = {}; state.nodeStyles = {};
    state.edgeStart = null; state.hover = null;
    stopForce(); parseInput(); draw();
  }
}

});

input.addEventListener('input', () => { parseInput(); draw(); });

// ---------- 初始化 ---------- load(); applyTheme(); input.value = state.inputText; document.getElementById('toggleDirected').textContent = state.directed ? '有向图' : '无向图'; document.querySelectorAll('#toolbar button[data-index]').forEach(b => { const v = b.dataset.index === 'custom' ? 'custom' : parseInt(b.dataset.index); b.classList.toggle('active', v === state.indexMode); }); bindSettings(); updateSettingsUI(); parseInput(); resize(); window.addEventListener('resize', resize); })(); </script> </body> </html>


:::