Compare commits

...
Author SHA1 Message Date
qiqi 73a29715d3 fix(image-annotate): v1.9.1 文字输入框贴住点击点、选区图标归位、底色一选就生效
1) 输入框偏到左上:showTextInput 用 canvasStack 的矩形换算,但 stack 尺寸是
(imgW + 2*overlayPad)*scale、图片在 stack 内还偏移 pad*scale(图层 canvas 的
left/top)。比例偏小又漏偏移,两个误差同向叠加。改用 textCanvas 的矩形
(与图层 canvas 同基准,精确等于图片显示区域),并按 textarea 的边框 2px +
内边距 8/4px 反向偏移,让输入框里的文字起点正压在点击点上;提交后
drawTextObject 也从 t.x/t.y 起画,所见即所得。

2) 选「选择」工具后三个选区图标不见了:两处叠加。
   - selCmdHTML 排在 hint 之后,而 .iwb-opt-hint 带 margin-left:auto;
   - 更关键的是 .iwb-opt-sep 写成 margin: 0 4px 0 auto,分隔线自带 auto,
     会把分隔线之后的内容整组推到最右,选项栏排满时直接滚出可视区。
修法:分隔线只分组(margin: 0 2px),留白交给末尾 hint;选区按钮排在 hint 之前。
现在「文字」「选择」两个工具下都是同一组三个图标,未选中元素时也在。

3) 设了底色看不到:底色一直在画,只是「只改颜色没点开关」时 bgFill 仍是 false。
   - 改 bgColor 时自动打开 bgFill,按钮 active 同步;
   - 顺带修掉更硬的 bug:「底色」按钮只能开不能关 —— data-value 在生成 HTML 时
     写死,状态变了没人更新,每次点都传「开启」。改由 syncOptionBar 按当前状态翻面;
   - 默认底色透明度 0.55 → 0.68(浅色/花色底图上 0.55 太透,容易被当成没生效)。

harness 158 → 162 条全通(新增输入框落点误差 ≤3px、Esc 不留空对象、
选择工具未选中仍有 3 个图标、只选颜色即自动开底色);validate 9/9。
2026-11-08 20:53:58 +08:00
qiqi e699c22fa0 feat(image-annotate): v1.9.0 文字样式包、吸附参考线、圆角与最近色、复制到剪贴板
文字从「字号 + 颜色」扩到完整样式:字重(常规/粗/特粗)、对齐(左/中/右)、
行距、描边、底色块、多行(textarea + Shift+Enter)。新增叶子模块 text.js,
fontOf / textMetrics / textBox / drawTextObject 成为唯一事实来源,
objects.js(预览/命中/包围盒)与 layers.js(栅格化)共用,避免量一套画一套;
描边与底色撑大包围盒,手柄、吸附、缩略图随之变化。单行无描边无底色的老文字
包围盒与旧实现逐像素一致,老作业打开不变形。

吸附参考线:snap.js 只做纯计算。目标线为画布 0/中/满 + 其他可见元素的左中右、
上中下;阈值 6 屏幕像素按 viewScale() 折回图片像素,磁力不随缩放变大;
命中画洋红参考线(区别于选中框的橙),松手清空;Alt 全程禁用。
位图/文字/形状三条拖动路径都接,文字需补 b.x - t.x 原点偏移。

矩形圆角:shapeRadius 进 drawShape,半径夹到 min(w,h)/2,路径手写 arcTo
(不用 ctx.roundRect,老内核没有)。最近使用颜色最多 8 个,存 ctx.settings
跨会话保留,只有落定的改色才记录;色板改用事件委托以覆盖动态插入的色块。

导出「复制」:结果编成 PNG 写 ClipboardItem,可直接粘进聊天窗口/后台上传框
且不关闭编辑器。优先 createImageBitmap 绕开宿主 CSP 的 img-src 限制;
非安全上下文无 navigator.clipboard 时明确提示改用「导出」而非静默失败。

顺带修:选项栏中文双字标签加 white-space:nowrap(否则 36px 一行内竖排成
「常/规」);.iwb-editor-optionbar-tip 补基础样式(原来只有 display:none,
裸 span 参与 flex 收缩被挤成两行贴边);文字工具的 hint 移到按钮之后,
放不下时让说明滚出视野而不是把操作按钮顶没。

harness 140 → 158 条,全部通过;validate 9/9。
2026-11-08 20:27:32 +08:00
17 changed files with 1826 additions and 106 deletions

No files matched your search

+107
View File
@@ -234,6 +234,113 @@ P 下双击 = 结束当前路径(`commitPenPath`),不再进节点编辑。
- 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。 - 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。
- 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。 - 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。
## v1.9.1:输入框贴住点击点 / 选区图标归位 / 底色一选就亮
v1.9.0 上线后用户反馈的三处「操作与实际反应不相符」。
### 1. 文字输入框跑到点击点的左上方
`showTextInput()` 用 `canvasStack` 的矩形换算屏幕坐标,但 stack 的尺寸是
`(imgW + 2 × overlayPad) × scale`,图片在 stack 内部还额外偏移了 `pad × scale`
(图层 canvas 的 `left/top`)。拿它算比例会偏小、又漏掉这段偏移,两个误差同向叠加,
输入框就整体挪到了左上。改为用 `textCanvas` 的矩形(与图层 canvas 同基准,
精确等于图片显示区域),并按 `textarea` 的边框 2px + 内边距 8/4px 反向偏移,
让「输入框里文字的起点」正好压在点击点上——提交后 `drawTextObject` 也从 `t.x/t.y` 起画,
两者位置一致。
### 2. 选「选择」工具那三个选区图标就不见了
两个原因叠在一起:
- 兜底分支里 `selCmdHTML()` 排在 `hint` **之后**,而 `.iwb-opt-hint` 带 `margin-left: auto`,
会把自己和后面的一切推到最右;
- 更关键的是 `.iwb-opt-sep` 写成了 `margin: 0 4px 0 auto`——分隔线自带 `auto`,
会把**分隔线之后的内容整组**推到最右侧。选项栏一旦排满(文字样式那一行),
这组按钮就被顶出可视区。
修法:分隔线只负责分组(`margin: 0 2px`),留白交给末尾的 `hint`;
选区按钮排在 `hint` 之前。现在「文字」和「选择」两个工具下都是同一组三个图标,
且未选中任何元素时也在(选区命令本来就是全局的)。
### 3. 设了文字底色却看不到
底色其实一直在画,问题是:**只改颜色、没点「底色」开关**时 `bgFill` 仍是 `false`,
画布上什么都不会变。用户于是以为底色没生效,或者被别的颜色盖住了。
- 改 `bgColor` 时自动把 `bgFill` 打开(选了颜色就是要用它),按钮的 `active` 同步亮起;
- 顺带修掉一个更硬的 bug:**「底色」按钮只能开、不能关**。它的 `data-value`
在生成 HTML 时就写死成 `${v.bgFill ? '0' : '1'}`,状态变了没人更新,
于是每次点击都传「开启」。现在 `syncOptionBar()` 会按当前状态翻面。
- 默认底色透明度 0.55 → 0.68:浅色/花色底图上 0.55 太透,容易被当成没生效。
回归:`tools/harness.mjs` **162 条全部通过**(新增输入框落点误差 ≤3px、
Esc 取消不留空对象、选择工具未选中仍有 3 个图标、只选颜色即自动开底色 4 条)。
## v1.9.0:文字样式包 / 吸附参考线 / 圆角与最近色 / 复制到剪贴板
一次补齐四个高频缺口,都属于「没有它就得切回 PS」的那类。
### 1. 文字从「字号 + 颜色」扩到完整样式
`字号 / 字重(常规·粗·特粗)/ 对齐(左·中·右)/ 行距 / 描边 / 底色块 / 多行`。
关键是把「量出来的框」和「画出来的字」合成一处:新增叶子模块 `text.js`,
`fontOf / textMetrics / textBox / drawTextObject` 是唯一事实来源,
`objects.js`(预览、命中、包围盒)与 `layers.js`(栅格化进矢量层)都调它。
此前量 `measureText` 一套、画 `fillText` 一套,一旦加描边和底色必然错位。
- 描边与底色会**撑大包围盒**(`textBox()` 计入 `strokeWidth/2` 与 padding),
选择框、吸附、缩放手柄随之变化,不会出现「字比框大」。
- 输入框从 `<input>` 换成 `<textarea rows="1">`:Enter 提交、**Shift+Enter 换行**、
Esc 取消,`input` 时按 `scrollHeight` 自适应高度。
- 单行 + 无描边 + 无底色的老文字,`textBox()` 与旧实现逐像素一致 ——
已有作业打开不变形。
- 新建文字继承当前默认样式(`S.textWeight` 等),不必每段重调。
### 2. 拖动吸附(画布中心/边缘 + 其他元素对齐)
`snap.js` 只做纯计算:给一个盒子和「别人的盒子」,返回最小位移与命中的参考线。
- 目标线 = 画布 `0 / 中 / 满` + 其他**可见**元素的左/中/右、上/中/下。
- 阈值 `6` 屏幕像素,按 `viewScale()` 折回图片像素再比较 —— **磁力不随缩放变大**,
放到 400% 也不会一拖就黏。
- 命中后画洋红参考线(`#ff2d95`,刻意区别于选中框的橙 `#e8a735`),松手清空。
- **按住 Alt 全程禁用**,需要精细摆放时不用去关开关。
- 位图 / 文字 / 形状三条拖动路径都接了。文字因为 `textBox()` 相对原点有偏移,
必须把 `b.x - t.x` 补回坐标再算,否则吸附中心会偏半个描边。
### 3. 矩形圆角 + 最近使用颜色
- `shapeRadius` 进 `drawShape`,半径夹到 `min(w, h)/2`;路径手写 `moveTo + 4×arcTo`,
不用 `ctx.roundRect`(老内核没有)。
- 最近使用颜色最多 8 个,去重、新的在前,存 `ctx.settings`(**跨会话保留**)。
只有**落定**的改色才记录,拖色板滑杆过程中的中间色不会灌进来。
- 色板改事件委托:最近色色块是动态插入的,直接逐个绑定会漏。
### 4. 导出「复制到剪贴板」
顶栏「导出」左边新增「复制」:把当前结果编码成 PNG 塞进 `ClipboardItem`,
可直接粘到聊天窗口 / 后台上传框,**不关闭编辑器**。
- 走 `toPngBlob()`,优先 `createImageBitmap` —— 宿主页 CSP 常禁 `img-src: blob:`,
用 `new Image()` 解码会直接失败。
- 失败必须**说清楚**:非安全上下文(如 `about:blank`)没有 `navigator.clipboard`,
提示「当前浏览器不支持复制图片,请用「导出」下载」,而不是静默无反应。
真实 https / localhost 下已验证可用(`navigator.clipboard.read()` 能读回 `image/png`)。
### 两条踩过的坑
1. **esbuild 打成 IIFE 后,循环 import 会变成 `undefined`**。新逻辑一律放只 import
`state.js` 的叶子模块(`text.js` / `snap.js` / `recent-colors.js`),
不要为省一个文件把它们并进 `objects.js`。
2. **选项栏里的中文双字标签必须 `white-space: nowrap`**,否则挤进 36px 高的一行会竖排
成「常/规」。另外说明文字(hint)要排在按钮**之后**:真放不下时宁可让说明滚出视野,
也不能把「复制 / 取消选区」这类按钮顶没。
回归:`tools/harness.mjs` 由 140 条增到 **158 条,全部通过**(新增多行包围盒、
字重/描边/底色生效并可撤销、吸附误差 < 1px、Alt 禁用、参考线松手清除、
圆角切角、最近色入弹层、复制有明确反馈等)。
## v1.8.3:图层面板交互修复(滑杆能拖、图层能拖排) ## v1.8.3:图层面板交互修复(滑杆能拖、图层能拖排)
线上两个反馈,根子在同一个属性上: 线上两个反馈,根子在同一个属性上:
+3 -1
View File
@@ -134,7 +134,7 @@
| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 | | 只有 PNG | 无 JPG/WebP、无质量控制 | P4 |
| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 | | 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 |
| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) | | 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) |
| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 | | ~~无下载 / 复制到系统剪贴板~~ | ✅ v1.9.0:顶栏「导出」下载;「复制」把结果编成 PNG 写 `ClipboardItem`,粘进聊天窗口/后台上传框,不关闭编辑器。非安全上下文无 `navigator.clipboard` 时明确提示改用导出 | 已完成 |
| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 | | 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 |
| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) | | 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) |
@@ -311,6 +311,7 @@ getCompositeCanvas() // 当前这一张
| 工具参数解耦与选项栏 | ✅ v1.2.0:`S.shapeLineWidth` / `S.textSize` 独立于 `S.brushSize`;选项栏按工具出参数(画笔三参、形状线宽+填充、文字字号、选区形状/羽化),与右侧面板双向同步 | | 工具参数解耦与选项栏 | ✅ v1.2.0:`S.shapeLineWidth` / `S.textSize` 独立于 `S.brushSize`;选项栏按工具出参数(画笔三参、形状线宽+填充、文字字号、选区形状/羽化),与右侧面板双向同步 |
| P3 图层增强 | 🟡 v1.7:缩略图 / 重命名 / 多选 / 不透明度滑杆已补;混合模式 / 图层蒙版 / 编组未做 | | P3 图层增强 | 🟡 v1.7:缩略图 / 重命名 / 多选 / 不透明度滑杆已补;混合模式 / 图层蒙版 / 编组未做 |
| P4 单张输出 | ✅ PNG/JPG/WebP、透明/白底、800×800(长边 80%)、≤500KB 迭代降质、下载、设置记忆;无队列 | | P4 单张输出 | ✅ PNG/JPG/WebP、透明/白底、800×800(长边 80%)、≤500KB 迭代降质、下载、设置记忆;无队列 |
| 文字样式与吸附 | ✅ v1.9.0:文字补字重/对齐/行距/描边/底色块/多行(`text.js` 统一量算与绘制,描边底色撑大包围盒);拖动吸附画布中心/边缘 + 其他元素,阈值按屏幕像素折算故不随缩放变化,Alt 禁用;矩形圆角;最近使用颜色(存 `ctx.settings`,跨会话) |
| 历史快照升级 | ✅ `snapshotState()` 记录完整图层集合(含 image 引用),能撤销「新建/删除图层」,这是复制新层与还原原图可撤销的前提 | | 历史快照升级 | ✅ `snapshotState()` 记录完整图层集合(含 image 引用),能撤销「新建/删除图层」,这是复制新层与还原原图可撤销的前提 |
| 历史面板 / 多选 / 亮色主题 / 草稿 | ⏳ P3/P5 | | 历史面板 / 多选 / 亮色主题 / 草稿 | ⏳ P3/P5 |
@@ -328,6 +329,7 @@ getCompositeCanvas() // 当前这一张
| 魔棒 | 宿主 CSP 未放行 `worker-src blob:` ⇒ 不能用 Worker 做连通域;放二期,主线程分块 + 让出帧,且限制最大像素数 | | 魔棒 | 宿主 CSP 未放行 `worker-src blob:` ⇒ 不能用 Worker 做连通域;放二期,主线程分块 + 让出帧,且限制最大像素数 |
| CSP | 单文件经典脚本 IIFE;禁 `eval` / `new Function` / ESM / CDN;样式 JS 注入 `<style>`;`toBlob` 要求 origin-clean ⇒ 远程图片必须 `fetch → blob → dataURL`(现有 `onPaste` 已按此实现) | | CSP | 单文件经典脚本 IIFE;禁 `eval` / `new Function` / ESM / CDN;样式 JS 注入 `<style>`;`toBlob` 要求 origin-clean ⇒ 远程图片必须 `fetch → blob → dataURL`(现有 `onPaste` 已按此实现) |
| 宿主争抢 paste | 宿主在 window 气泡阶段也监听粘贴(建 ref 节点 + 下载)。编辑器继续在 document 捕获阶段 `stopImmediatePropagation()`。新增「复制选区到系统剪贴板」需要 `ClipboardItem` + 用户手势 + 权限,失败必须有 toast 降级 | | 宿主争抢 paste | 宿主在 window 气泡阶段也监听粘贴(建 ref 节点 + 下载)。编辑器继续在 document 捕获阶段 `stopImmediatePropagation()`。新增「复制选区到系统剪贴板」需要 `ClipboardItem` + 用户手势 + 权限,失败必须有 toast 降级 |
| 选项栏横向排布 | `.iwb-editor-optionbar-body` 是 `overflow-x: auto` 的 flex。**任何 `margin-left: auto` 都会把其后内容整组推到最右**,排满时直接滚出可视区 —— `v1.9.1` 就是 `.iwb-opt-sep` 带了 `auto`,导致选区按钮在选择工具下「消失」。留白只允许放在末尾的 `.iwb-opt-hint`;中文双字按钮必须 `white-space: nowrap`,否则会竖排 |
| 草稿持久化 | `ctx.storage` 是 localStorage 命名空间小 KV(`get/set/remove/keys`),**不能塞像素**;`ctx.settings` 适合存输出预设与面板开合。若要做工程草稿,只能存元数据 + 宿主节点引用;真要存图层像素需插件自建 IndexedDB 库(必须自带 `onupgradeneeded` 建表,宿主踩过这个坑)或与宿主协商新能力 | | 草稿持久化 | `ctx.storage` 是 localStorage 命名空间小 KV(`get/set/remove/keys`),**不能塞像素**;`ctx.settings` 适合存输出预设与面板开合。若要做工程草稿,只能存元数据 + 宿主节点引用;真要存图层像素需插件自建 IndexedDB 库(必须自带 `onupgradeneeded` 建表,宿主踩过这个坑)或与宿主协商新能力 |
| 节点模型 | 宿主 `setNodeImage` / `createImageNode` 只收一张图;导出即扁平化。要做「可继续编辑的工程」需要宿主侧支持节点附加数据 ⇒ 属于跨仓变更,P5 再评估 | | 节点模型 | 宿主 `setNodeImage` / `createImageNode` 只收一张图;导出即扁平化。要做「可继续编辑的工程」需要宿主侧支持节点附加数据 ⇒ 属于跨仓变更,P5 再评估 |
| 上游关系 | 编辑器移植自 `iwb-plaus/iwb-cutout-extension`,README 已警告 1.0.5 的 z 序修复不能整目录覆盖回去。P0 的大改等于正式分叉,应在 README 明确改为「一次性移植 + 独立演进」,避免以后误回灌 | | 上游关系 | 编辑器移植自 `iwb-plaus/iwb-cutout-extension`,README 已警告 1.0.5 的 z 序修复不能整目录覆盖回去。P0 的大改等于正式分叉,应在 README 明确改为「一次性移植 + 独立演进」,避免以后误回灌 |
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@iwb-plugin/image-annotate", "name": "@iwb-plugin/image-annotate",
"private": true, "private": true,
"version": "1.8.3", "version": "1.9.1",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)", "description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": { "ibwPlugin": {
"id": "image-annotate", "id": "image-annotate",
+67 -2
View File
@@ -563,10 +563,17 @@
border: 2px solid #4488ff; border: 2px solid #4488ff;
border-radius: 4px; border-radius: 4px;
font-size: 14px; font-size: 14px;
line-height: 1.35;
/* textarea:默认会显示右下角拖拽柄与滚动条,画布上的就地输入框都不要 */
resize: none;
overflow: hidden;
white-space: pre;
background: rgba(255, 255, 255, 0.95); background: rgba(255, 255, 255, 0.95);
color: #1e1e2e; color: #1e1e2e;
z-index: 10; z-index: 10;
min-width: 120px; min-width: 120px;
min-height: 30px;
font-family: inherit;
} }
.iwb-editor-text-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(68, 136, 255, 0.3); } .iwb-editor-text-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(68, 136, 255, 0.3); }
@@ -1434,6 +1441,12 @@
} }
.iwb-editor-optionbar-label { color: #7f849c; font-weight: 600; white-space: nowrap; } .iwb-editor-optionbar-label { color: #7f849c; font-weight: 600; white-space: nowrap; }
.iwb-editor-optionbar-body { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; min-width: 0; } .iwb-editor-optionbar-body { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; min-width: 0; }
/* 右端通用快捷键提示。原来只有 @media 里的 display:none,没有任何基础样式,
于是它作为裸 span 参与 flex 收缩,被挤成两行还贴到右边缘外。 */
.iwb-editor-optionbar-tip {
flex: 0 0 auto; white-space: nowrap;
color: #6c7086; font-size: 11px; padding-left: 4px;
}
.iwb-opt-label { color: #a6adc8; white-space: nowrap; } .iwb-opt-label { color: #a6adc8; white-space: nowrap; }
.iwb-opt-btn { .iwb-opt-btn {
background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px; background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;
@@ -1446,7 +1459,10 @@
border: 1px solid #45475a; border-radius: 5px; text-align: center; font-size: 12px; border: 1px solid #45475a; border-radius: 5px; text-align: center; font-size: 12px;
} }
.iwb-opt-current { color: #e8a735; font-weight: 600; white-space: nowrap; } .iwb-opt-current { color: #e8a735; font-weight: 600; white-space: nowrap; }
.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* hint 是「说明」不是「控件」:不许被压缩。
早先带 text-overflow:ellipsis,在 36px 高的选项栏里会被压成「双击改…」这种半截文案,
比不显示更误导人;现在由父级 overflow-x 决定是完整显示还是整体滚出视野。 */
.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; flex: 0 0 auto; }
.iwb-editor-more-wrap, .iwb-editor-export-settings-wrap { position: relative; flex: 0 0 auto; z-index: 45; } .iwb-editor-more-wrap, .iwb-editor-export-settings-wrap { position: relative; flex: 0 0 auto; z-index: 45; }
.iwb-editor-more-btn, .iwb-editor-panel-toggle, .iwb-editor-export-settings-btn { .iwb-editor-more-btn, .iwb-editor-panel-toggle, .iwb-editor-export-settings-btn {
@@ -1658,7 +1674,11 @@
.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; } .iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; }
.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:disabled { opacity: 0.35; cursor: not-allowed; } .iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:disabled { opacity: 0.35; cursor: not-allowed; }
/* 选区命令(全选/反选/取消):v1.2.5 起放在「选择」工具的选项栏里,不再占竖工具条 */ /* 选区命令(全选/反选/取消):v1.2.5 起放在「选择」工具的选项栏里,不再占竖工具条 */
.iwb-opt-sep { width: 1px; height: 18px; background: #313244; margin: 0 4px 0 auto; flex: 0 0 auto; } /* 分隔线只负责「分组」,不负责「推到右边」。
原来写的是 margin: 0 4px 0 auto —— auto 会把分隔线之后的内容整组推到最右侧,
在选项栏已经排满的情况下(文字样式那一行)直接把后面的选区按钮顶出可视区,
看起来就是「这个工具下没有那几个按钮」。留白交给末尾的 .iwb-opt-hint。 */
.iwb-opt-sep { width: 1px; height: 18px; background: #313244; margin: 0 2px; flex: 0 0 auto; }
.iwb-opt-selcmd { .iwb-opt-selcmd {
width: 26px; height: 26px; min-width: 26px; padding: 0; border: 0; border-radius: 7px; width: 26px; height: 26px; min-width: 26px; padding: 0; border: 0; border-radius: 7px;
background: #26263a; color: #cdd6f4; flex: 0 0 auto; background: #26263a; color: #cdd6f4; flex: 0 0 auto;
@@ -1858,3 +1878,48 @@
border-color: #89b4fa; border-color: #89b4fa;
color: #cdd6f4; color: #cdd6f4;
} }
/* ================================================================
v1.9:文字样式控件 / 圆角 / 最近使用颜色 / 复制按钮
================================================================ */
/* 选项栏里的原生颜色框(描边色 / 底色):压成和数字框同高的小方块 */
.iwb-opt-color {
width: 22px;
height: 20px;
padding: 0;
flex: 0 0 auto;
border: 1px solid #45475a;
border-radius: 4px;
background: transparent;
cursor: pointer;
}
.iwb-opt-color::-webkit-color-swatch-wrapper { padding: 2px; }
.iwb-opt-color::-webkit-color-swatch { border: 0; border-radius: 3px; }
/* 「最近使用」:色板弹层里 4 列 × 2 行,空的时候整块隐藏(不占位) */
.iwb-editor-color-pop .iwb-editor-recent-colors {
display: grid;
grid-template-columns: repeat(4, 18px);
grid-auto-rows: 18px;
gap: 5px;
flex: 0 0 auto;
align-content: center;
}
.iwb-editor-recent-colors[hidden] { display: none; }
.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch {
width: 18px;
height: 18px;
padding: 0;
border: 0;
border-radius: 50%;
cursor: pointer;
}
.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }
/* 复制到剪贴板:与「导出」同尺寸但用低饱和色,避免两个绿色按钮抢眼 */
.iwb-editor-btn-copy { background: #313244 !important; color: #cdd6f4 !important; }
.iwb-editor-btn-copy:hover { background: #3b3d52 !important; }
/* 选项栏按钮里是中文双字标签(常规/特粗/底色),不给 nowrap 会被挤成竖排 */
.iwb-editor-optionbar-body .iwb-opt-btn { white-space: nowrap; }
+6 -2
View File
@@ -79,13 +79,14 @@ import { bindEvents } from './events.js'
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div> <div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
</div> </div>
</div> </div>
<button class="iwb-editor-btn iwb-editor-btn-copy" data-action="copyClipboard" title="复制当前结果到系统剪贴板(可直接粘到聊天窗口/后台),不关闭编辑器">复制</button>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button> <button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button>
</div> </div>
</div> </div>
<div class="iwb-editor-optionbar"> <div class="iwb-editor-optionbar">
<span class="iwb-editor-optionbar-label">工具选项</span> <span class="iwb-editor-optionbar-label">工具选项</span>
<div class="iwb-editor-optionbar-body"></div> <div class="iwb-editor-optionbar-body"></div>
<span class="iwb-editor-optionbar-tip">选区也可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消</span> <span class="iwb-editor-optionbar-tip" title="选中后还可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消选区">Ctrl+J 复制 · Delete 清除</span>
</div> </div>
<div class="iwb-editor-main"> <div class="iwb-editor-main">
@@ -114,7 +115,8 @@ import { bindEvents } from './events.js'
<canvas class="iwb-editor-selection-overlay"></canvas> <canvas class="iwb-editor-selection-overlay"></canvas>
<canvas class="iwb-editor-cursor-overlay"></canvas> <canvas class="iwb-editor-cursor-overlay"></canvas>
</div> </div>
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消"> <!-- v1.9:input → textarea,支持 Shift+Enter 换行(Enter 仍是确认) -->
<textarea class="iwb-editor-text-input" rows="1" wrap="off" placeholder="输入文字,Enter 确认,Shift+Enter 换行" spellcheck="false"></textarea>
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div> <div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 --> <!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 -->
<div class="iwb-editor-sel-bar"> <div class="iwb-editor-sel-bar">
@@ -239,6 +241,8 @@ import { bindEvents } from './events.js'
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效"> <input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
</div> </div>
<span class="iwb-color-pop-sep"></span> <span class="iwb-color-pop-sep"></span>
<!-- 最近使用(v1.9):由 recent-colors.js 动态填充,空的时候整行隐藏 -->
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
<div class="iwb-editor-color-swatches"> <div class="iwb-editor-color-swatches">
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button> <button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button> <button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button>
+219 -16
View File
@@ -15,9 +15,10 @@ import { beginMarquee, updateMarquee, endMarquee, beginLasso, updateLasso, endLa
import { runCommand, toast } from './commands.js' import { runCommand, toast } from './commands.js'
import { showSelectionContext, hideSelectionContext } from './floating.js' import { showSelectionContext, hideSelectionContext } from './floating.js'
import { applyConstraintDrag, cancelCrop, clearOverlay, confirmCrop, drawCropPreview, hideCropBar, hitCropHandle, insideRect, resizeCropRect, setConstraint, showCropBar, updateCropInfo } from './crop.js' import { applyConstraintDrag, cancelCrop, clearOverlay, confirmCrop, drawCropPreview, hideCropBar, hitCropHandle, insideRect, resizeCropRect, setConstraint, showCropBar, updateCropInfo } from './crop.js'
import { applyShapeHandle, beginPenEdit, beginShapeHandleDrag, beginTextRotate, beginTextScaleDrag, commitTextInput, deleteSelectedShape, deleteSelectedText, exitPenEdit, getPenEditingShape, getSelectedShape, getSelectedText, hideTextInput, hitAnyObject, hitPenEdgeInsert, hitPenPoint, hitShapeHandle, hitShapeLayer, hitTextHandle, hitTextLayer, hitTopmost, moveLayer, renderObjects, selectNeighborLayer, selectUnit, shapeBounds, showTextInput } from './objects.js' import { applyShapeHandle, beginPenEdit, beginShapeHandleDrag, beginTextRotate, beginTextScaleDrag, commitTextInput, deleteSelectedShape, deleteSelectedText, exitPenEdit, getPenEditingShape, getSelectedShape, getSelectedText, hideTextInput, hitAnyObject, hitPenEdgeInsert, hitPenPoint, hitShapeHandle, hitShapeLayer, hitTextHandle, hitTextLayer, hitTopmost, moveLayer, otherObjectBoxes, renderObjects, selectNeighborLayer, selectUnit, shapeBounds, showTextInput, textBounds } from './objects.js'
import { snapMove } from './snap.js'
import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitPlacementHandle, insidePlacementRect, resizePlacement } from './placement.js' import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitPlacementHandle, insidePlacementRect, resizePlacement } from './placement.js'
import { close, exportResult } from './index.js' import { close, copyResult, exportResult } from './index.js'
import { loadImage } from './dom.js' import { loadImage } from './dom.js'
import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js' import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js'
import { applyQuickEffect, setEffectValue } from './effects.js' import { applyQuickEffect, setEffectValue } from './effects.js'
@@ -344,6 +345,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
function onMouseMove(e) { function onMouseMove(e) {
// 记下修饰键:拖动按 Alt 时临时关掉吸附(想停在「差一点点」的位置时用)
S._altDown = !!e.altKey
// 图片放置拖拽 // 图片放置拖拽
if (S.placingImage && S.placingHandle && S.placingStart) { if (S.placingImage && S.placingHandle && S.placingStart) {
onPlacementDragMove(e); return onPlacementDragMove(e); return
@@ -416,8 +419,24 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (S.textDrag.mode === 'move') { if (S.textDrag.mode === 'move') {
const dx = pos0.x - S.textDrag.start.x const dx = pos0.x - S.textDrag.start.x
const dy = pos0.y - S.textDrag.start.y const dy = pos0.y - S.textDrag.start.y
t.x = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4)) let nx = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4))
t.y = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4)) let ny = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4))
// 吸附:按住 Alt 临时关掉(要对齐到「差一点点」的位置时用)
if (!S._altDown) {
const b = textBounds(t)
// b 是「含描边/底色的包围盒」,t.x/t.y 是文字原点:两者差一个固定偏移,
// 用原点当包围盒左上会把吸附中心算偏 strokeWidth/2,边线永远差几像素吸不上
const offX = b.x - t.x
const offY = b.y - t.y
const s = snapMove({ x: nx + offX, y: ny + offY, w: b.w, h: b.h }, otherObjectBoxes(t))
nx += s.dx
ny += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
t.x = nx
t.y = ny
} else if (S.textDrag.mode === 'rotate') { } else if (S.textDrag.mode === 'rotate') {
const st = S.textDrag const st = S.textDrag
const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx) const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx)
@@ -457,8 +476,17 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const dx = pos0.x - S.shapeDrag.start.x const dx = pos0.x - S.shapeDrag.start.x
const dy = pos0.y - S.shapeDrag.start.y const dy = pos0.y - S.shapeDrag.start.y
const b = shapeBounds(S.shapeDrag.shape) const b = shapeBounds(S.shapeDrag.shape)
const cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w))) let cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)))
const cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h))) let cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)))
if (!S._altDown) {
const box = { x: b.x + cdx, y: b.y + cdy, w: b.w, h: b.h }
const s = snapMove(box, otherObjectBoxes(sh))
cdx += s.dx
cdy += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
if (sh.type === 'pen') { if (sh.type === 'pen') {
sh.pts = (S.shapeDrag.shape.pts || []).map(p => ({ x: p.x + cdx, y: p.y + cdy })) sh.pts = (S.shapeDrag.shape.pts || []).map(p => ({ x: p.x + cdx, y: p.y + cdy }))
} else { } else {
@@ -510,6 +538,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
lw: Math.max(1, S.shapeLineWidth), lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth), lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false, fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
opacity: 1, opacity: 1,
visible: true visible: true
} }
@@ -622,6 +651,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
} }
S.textDrag = null S.textDrag = null
S.guides = null // 松手即撤掉吸附参考线(重绘 overlay 才能真的擦掉)
renderObjects()
renderLayerPanel() renderLayerPanel()
return return
} }
@@ -639,6 +670,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
} }
S.bitmapDrag = null S.bitmapDrag = null
S.guides = null
renderObjects() renderObjects()
renderLayerPanel() renderLayerPanel()
return return
@@ -656,6 +688,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
} }
S.shapeDrag = null S.shapeDrag = null
S.guides = null
renderObjects()
renderLayerPanel() renderLayerPanel()
return return
} }
@@ -708,6 +742,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
color: S.color, color: S.color,
lw: Math.max(1, S.shapeLineWidth), lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false, fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
opacity: 1, opacity: 1,
visible: true, visible: true,
locked: false, locked: false,
@@ -946,6 +981,51 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const SHAPE_NAMES = { rect: '矩形', circle: '圆形', arrow: '箭头', pen: '钢笔路径' } const SHAPE_NAMES = { rect: '矩形', circle: '圆形', arrow: '箭头', pen: '钢笔路径' }
// ---- 文字样式(v1.9):字重 / 对齐 / 行距 / 描边 / 底色 ----
// 控件既作用于「当前选中的文字」,也写回「新建文字的默认值」:
// 没选中时光调参数就是调下一次输入的样子,选中后调则立刻改这一段。
const TEXT_STYLE_STATE_KEY = {
fontWeight: 'textWeight', align: 'textAlign', lineHeight: 'textLineHeight',
strokeWidth: 'textStrokeWidth', strokeColor: 'textStrokeColor',
bgFill: 'textBgFill', bgColor: 'textBgColor'
}
/** 读样式:t 有值读对象自己的(老对象缺字段时回退到默认),否则读新建默认值 */
function textStyleValues(t) {
const pick = (objKey, stateKey, dflt) => {
const raw = t ? t[objKey] : S[stateKey]
return raw == null ? dflt : raw
}
return {
fontWeight: String(pick('fontWeight', 'textWeight', 'bold')),
align: pick('align', 'textAlign', 'left'),
lineHeight: Number(pick('lineHeight', 'textLineHeight', 1.25)) || 1.25,
strokeWidth: Math.max(0, Number(pick('strokeWidth', 'textStrokeWidth', 0)) || 0),
strokeColor: pick('strokeColor', 'textStrokeColor', '#ffffff'),
bgFill: !!pick('bgFill', 'textBgFill', false),
bgColor: pick('bgColor', 'textBgColor', '#000000')
}
}
function textStyleHTML(t) {
const v = textStyleValues(t)
const wBtn = (val, label, title) =>
`<button class="iwb-opt-btn${v.fontWeight === val ? ' active' : ''}" data-opt-text="fontWeight" data-value="${val}" title="${title}">${label}</button>`
const aBtn = (val, label, title) =>
`<button class="iwb-opt-btn${v.align === val ? ' active' : ''}" data-opt-text="align" data-value="${val}" title="${title}">${label}</button>`
return `<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">字重</span>${wBtn('normal', '常规', '常规字重')}${wBtn('bold', '粗', '粗体(默认)')}${wBtn('900', '特粗', '特粗,封面标题用')}
<span class="iwb-opt-label">对齐</span>${aBtn('left', '左', '多行时按左缘对齐')}${aBtn('center', '中', '多行时居中')}${aBtn('right', '右', '多行时按右缘对齐')}
<span class="iwb-opt-label">行距</span>
<input type="number" class="iwb-opt-num" data-opt="textLineHeight" min="80" max="300" step="5" value="${Math.round(v.lineHeight * 100)}"><span class="iwb-opt-unit">%</span>
<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">描边</span>
<input type="number" class="iwb-opt-num" data-opt="textStrokeWidth" min="0" max="40" step="1" value="${Math.round(v.strokeWidth)}"><span class="iwb-opt-unit">px</span>
<input type="color" class="iwb-opt-color" data-opt-color="strokeColor" value="${v.strokeColor}" title="描边颜色">
<button class="iwb-opt-btn${v.bgFill ? ' active' : ''}" data-opt-text="bgFill" data-value="${v.bgFill ? '0' : '1'}" title="给文字加一块半透明底色,压在花背景上也能看清">底色</button>
<input type="color" class="iwb-opt-color" data-opt-color="bgColor" value="${v.bgColor}" title="底色颜色;选色会自动开启底色,不用先点左侧按钮">`
}
/** 选择工具:只有选中了元素才出该元素的参数。 /** 选择工具:只有选中了元素才出该元素的参数。
* 用户裁定 2026-11-04:选中矩形/钢笔后要能就地切描边/实心、改描边粗细, * 用户裁定 2026-11-04:选中矩形/钢笔后要能就地切描边/实心、改描边粗细,
* 不必再切回绘制工具 —— 所以这里复用绘制工具同一套控件与写回路径。 */ * 不必再切回绘制工具 —— 所以这里复用绘制工具同一套控件与写回路径。 */
@@ -972,6 +1052,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>` return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>`
+ rangeOpt('shapeLineWidth', '线宽', 1, 60, lw, '') + rangeOpt('shapeLineWidth', '线宽', 1, 60, lw, '')
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24]) + presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
// 圆角只对矩形有意义(圆形本来就是圆的,箭头/钢笔没有这个概念)
+ (t === 'rect' ? rangeOpt('shapeRadius', '圆角', 0, 200, Math.round(sh.radius || 0), 'px') : '')
+ (t === 'arrow' ? '' : fillStyleHTML(owner)) + (t === 'arrow' ? '' : fillStyleHTML(owner))
+ (t === 'pen' && !sh.closed + (t === 'pen' && !sh.closed
? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>' ? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>'
@@ -983,12 +1065,18 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (text) { if (text) {
return `<span class="iwb-opt-current">已选中:文字</span>` return `<span class="iwb-opt-current">已选中:文字</span>`
+ rangeOpt('textSize', '字号', 8, 400, Math.round(text.fontSize || S.textSize), 'px') + rangeOpt('textSize', '字号', 8, 400, Math.round(text.fontSize || S.textSize), 'px')
+ '<span class="iwb-opt-hint">双击文字改内容,拖动移动,手柄缩放</span>' + textStyleHTML(text)
// 控件齐全时这一行很挤,说明文字必须排在按钮之后:
// 真放不下时宁可把 hint 滚出视野,也不能把「复制/取消选区」这些按钮顶没了
+ selCmdHTML() + selCmdHTML()
+ '<span class="iwb-opt-hint">双击改内容 · 拖动手柄缩放</span>'
} }
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span> // 选区命令是全局的,跟「有没有选中元素」无关:没选中时也必须能全选/反选/取消。
<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里会出现它的描边、实心与粗细</span>` // 关键是必须排在 hint **之前** —— hint 带 margin-left:auto,放它后面会被一路
// 推到最右侧,窄屏上直接滚出可视区,看起来就成了「选择工具下没有这三个按钮」。
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span>`
+ selCmdHTML() + selCmdHTML()
+ '<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里出现它的描边、实心与粗细</span>'
} }
/** 每个工具只露最常用的 2–4 个参数,全部直接写回 S(右侧参数面板同步) */ /** 每个工具只露最常用的 2–4 个参数,全部直接写回 S(右侧参数面板同步) */
@@ -1009,6 +1097,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (tool === 'rect' || tool === 'circle') { if (tool === 'rect' || tool === 'circle') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '') return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24]) + presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
+ (tool === 'rect' ? rangeOpt('shapeRadius', '圆角', 0, 200, S.shapeRadius, 'px') : '')
+ fillStyleHTML('rect') + fillStyleHTML('rect')
} }
if (tool === 'arrow') { if (tool === 'arrow') {
@@ -1024,7 +1113,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
if (tool === 'text') { if (tool === 'text') {
return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px') return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px')
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>' + textStyleHTML(null)
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认,Shift+Enter 换行</span>'
} }
if (tool === 'marquee') { if (tool === 'marquee') {
return `<span class="iwb-opt-label">形状</span> return `<span class="iwb-opt-label">形状</span>
@@ -1068,7 +1158,10 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (key === 'brushHardness') return S.brushHardness if (key === 'brushHardness') return S.brushHardness
if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100) if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100)
if (key === 'shapeLineWidth') return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth if (key === 'shapeLineWidth') return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth
if (key === 'shapeRadius') return selShape && selShape.type === 'rect' ? Math.round(selShape.radius || 0) : S.shapeRadius
if (key === 'textSize') return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize if (key === 'textSize') return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize
if (key === 'textLineHeight') return Math.round((selText ? (Number(selText.lineHeight) || S.textLineHeight) : S.textLineHeight) * 100)
if (key === 'textStrokeWidth') return Math.round(selText ? (Number(selText.strokeWidth) || 0) : S.textStrokeWidth)
if (key === 'feather') return S.selectionFeather if (key === 'feather') return S.selectionFeather
return '' return ''
} }
@@ -1093,6 +1186,25 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
btn.classList.toggle('active', !!cur === (btn.dataset.value === 'fill')) btn.classList.toggle('active', !!cur === (btn.dataset.value === 'fill'))
}) })
// 文字样式按钮组与两个颜色框:选中对象的值优先,没选中就显示新建默认值
const sv = textStyleValues(selText)
body.querySelectorAll('[data-opt-text]').forEach(btn => {
const k = btn.dataset.optText
// bgFill 是开关:active 直接看当前状态,data-value 必须随之翻面。
// 只在 HTML 里写死 ${v.bgFill ? '0' : '1'} 而这里不更新的话,
// 点一次能开、再点还是传「开」——按钮永远关不掉。
if (k === 'bgFill') {
btn.classList.toggle('active', !!sv.bgFill)
btn.dataset.value = sv.bgFill ? '0' : '1'
return
}
btn.classList.toggle('active', String(sv[k]) === btn.dataset.value)
})
body.querySelectorAll('[data-opt-color]').forEach(inp => {
if (document.activeElement === inp) return
const v = sv[inp.dataset.optColor]
if (v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v
})
} }
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */ /** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
@@ -1140,6 +1252,53 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (committed) textSnapDone = false if (committed) textSnapDone = false
} }
let textStyleSnapDone = false
/**
* 应用一条文字样式。
* 两件事一起做:写回「新建默认值」S.*,以及改当前选中的那段文字。
* 拖动滑杆/连续点按钮时只在第一次拍快照(一次调整 = 一次撤销)。
*/
function applyTextStyle(key, raw, committed) {
const stateKey = TEXT_STYLE_STATE_KEY[key]
if (!stateKey) return
let value = raw
// data-value 是字符串:'0' 也是真值,必须显式判,不能直接 !!raw
if (key === 'bgFill') value = raw === true || raw === 1 || raw === '1' || raw === 'true'
else if (key === 'lineHeight') value = clamp(Number(raw) || 125, 80, 300) / 100
else if (key === 'strokeWidth') value = clamp(Number(raw) || 0, 0, 40)
else if (key === 'strokeColor' || key === 'bgColor') value = String(raw || '#000000').toLowerCase()
else value = String(raw)
S[stateKey] = value
const t = getSelectedText()
if (!t || t.locked) { textStyleSnapDone = false; return }
if (committed || !textStyleSnapDone) { saveSnapshot('文字样式'); textStyleSnapDone = true }
t[key] = value
// 只调颜色、没点「底色」开关时,画布上什么都不会变 —— 这是最容易被当成
// 「底色坏了 / 被别的颜色盖住」的路径。选了颜色就说明想用它,顺手把底色打开。
if (key === 'bgColor' && !t.bgFill) {
t.bgFill = true
S.textBgFill = true
}
renderObjects()
// 自动开启底色后按钮的 active 态与色块取值都要跟着刷新
if (key === 'bgColor') syncOptionBar()
if (committed) textStyleSnapDone = false
}
let radiusSnapDone = false
/** 圆角只对矩形有意义:改默认值 + 改选中的那个矩形 */
function applyShapeRadius(committed) {
const sh = getSelectedShape()
if (!sh || sh.locked || sh.type !== 'rect') { radiusSnapDone = false; return }
if (committed || !radiusSnapDone) { saveSnapshot('圆角'); radiusSnapDone = true }
sh.radius = S.shapeRadius
renderObjects()
if (committed) radiusSnapDone = false
}
/** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个。 /** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个。
* owner='rect' 作用于矩形/圆,owner='pen' 作用于钢笔闭合路径。 */ * owner='rect' 作用于矩形/圆,owner='pen' 作用于钢笔闭合路径。 */
function setShapeFill(fill, owner) { function setShapeFill(fill, owner) {
@@ -1183,6 +1342,13 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} else if (key === 'textSize') { } else if (key === 'textSize') {
S.textSize = clamp(safe || 32, 8, 400) S.textSize = clamp(safe || 32, 8, 400)
applyTextSize(committed) applyTextSize(committed)
} else if (key === 'textLineHeight') {
applyTextStyle('lineHeight', safe || 125, committed)
} else if (key === 'textStrokeWidth') {
applyTextStyle('strokeWidth', safe, committed)
} else if (key === 'shapeRadius') {
S.shapeRadius = clamp(safe, 0, 400)
applyShapeRadius(committed)
} else if (key === 'feather') { } else if (key === 'feather') {
S.selectionFeather = clamp(safe, 0, 20) S.selectionFeather = clamp(safe, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
@@ -1268,8 +1434,28 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
// 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径, // 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径,
// committed 只决定「要不要顺手记一步历史」,不影响参数生效。 // committed 只决定「要不要顺手记一步历史」,不影响参数生效。
body.addEventListener('input', (e) => setOptionFromControl(e.target, false)) body.addEventListener('input', (e) => setOptionFromControl(e.target, false))
body.addEventListener('change', (e) => setOptionFromControl(e.target, true)) body.addEventListener('change', (e) => {
// 原生颜色框:拖动时只派发 input、关闭取色器才派发 change。
// 只认 change,保证「改一次颜色 = 一步撤销」,不在拖动途中连拍快照。
const colorEl = e.target.closest ? e.target.closest('[data-opt-color]') : null
if (colorEl) {
e.stopPropagation()
applyTextStyle(colorEl.dataset.optColor, colorEl.value, true)
syncOptionBar()
return
}
setOptionFromControl(e.target, true)
})
body.addEventListener('click', (e) => { body.addEventListener('click', (e) => {
// 文字样式按钮(字重 / 对齐 / 底色开关)
const textBtn = e.target.closest('[data-opt-text]')
if (textBtn) {
e.stopPropagation()
const k = textBtn.dataset.optText
applyTextStyle(k, textBtn.dataset.value, true)
syncOptionBar()
return
}
const shapeBtn = e.target.closest('[data-opt="shape"]') const shapeBtn = e.target.closest('[data-opt="shape"]')
if (shapeBtn) { if (shapeBtn) {
e.stopPropagation() e.stopPropagation()
@@ -1467,7 +1653,16 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
} }
const panelHexInput = runtime.el.querySelector('.iwb-editor-color-hex-input') const panelHexInput = runtime.el.querySelector('.iwb-editor-color-hex-input')
if (panelHexInput) panelHexInput.addEventListener('change', () => { if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value) }) if (panelHexInput) panelHexInput.addEventListener('change', () => { if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value) })
runtime.el.querySelectorAll('.iwb-editor-color-panel-swatch').forEach(btn => btn.addEventListener('click', (e) => { e.stopPropagation(); setPanelColor(btn.dataset.panelColor) })) // 色块统一走委托:静态 12 色 + 动态插入的「最近使用」都要能点,
// 一次性 querySelectorAll 绑定会漏掉后来插进来的按钮
if (pop) {
pop.addEventListener('click', (e) => {
const btn = e.target.closest('[data-panel-color]')
if (!btn) return
e.stopPropagation()
setPanelColor(btn.dataset.panelColor)
})
}
const palettePick = runtime.el.querySelector('[data-action="palettePick"]') const palettePick = runtime.el.querySelector('[data-action="palettePick"]')
if (palettePick) { if (palettePick) {
palettePick.addEventListener('mousedown', (e) => e.stopPropagation()) palettePick.addEventListener('mousedown', (e) => e.stopPropagation())
@@ -1658,6 +1853,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
// 底部 // 底部
bindIf('[data-action="cancel"]', 'click', close) bindIf('[data-action="cancel"]', 'click', close)
bindIf('[data-action="download"]', 'click', () => exportResult('download')) bindIf('[data-action="download"]', 'click', () => exportResult('download'))
bindIf('[data-action="copyClipboard"]', 'click', () => copyResult())
bindIf('[data-action="newNode"]', 'click', () => exportResult('newNode')) bindIf('[data-action="newNode"]', 'click', () => exportResult('newNode'))
bindIf('[data-action="replace"]', 'click', () => exportResult('replace')) bindIf('[data-action="replace"]', 'click', () => exportResult('replace'))
} }
@@ -1670,14 +1866,21 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
S.canvasWrap.addEventListener('wheel', onWheel, { passive: false }) S.canvasWrap.addEventListener('wheel', onWheel, { passive: false })
} }
/** 文字输入框:Enter 提交、Esc 取消 */ /** 文字输入框:Enter 提交、Shift+Enter 换行、Esc 取消(v1.9 换成 textarea 支持多行) */
function bindTextInput() { function bindTextInput() {
// 文字输入 // 文字输入
const textInput = runtime.el.querySelector('.iwb-editor-text-input') const textInput = runtime.el.querySelector('.iwb-editor-text-input')
textInput && textInput.addEventListener('mousedown', (e) => e.stopPropagation()) if (!textInput) return
textInput && textInput.addEventListener('keydown', (e) => { textInput.addEventListener('mousedown', (e) => e.stopPropagation())
// 边打边按内容撑高:textarea 不自动长高,多行标题会被压在两行里看不清
const autosize = () => {
textInput.style.height = 'auto'
textInput.style.height = (textInput.scrollHeight + 4) + 'px'
}
textInput.addEventListener('input', autosize)
textInput.addEventListener('keydown', (e) => {
e.stopPropagation() e.stopPropagation()
if (e.key === 'Enter') { e.preventDefault(); commitTextInput() } if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); commitTextInput() }
else if (e.key === 'Escape') { e.preventDefault(); hideTextInput() } else if (e.key === 'Escape') { e.preventDefault(); hideTextInput() }
}) })
} }
+61
View File
@@ -294,3 +294,64 @@ import { toast } from './commands.js'
setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000) setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000)
toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success') toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success')
} }
/** 任意图片 blob → PNG blob(剪贴板对 image/png 支持最稳,体积在剪贴板里无所谓) */
async function toPngBlob(blob) {
// 优先 createImageBitmap:不经过 URL,绕开宿主 CSP 对 img-src 的限制
try {
if (typeof createImageBitmap === 'function') {
const bmp = await createImageBitmap(blob)
const c = document.createElement('canvas')
c.width = bmp.width
c.height = bmp.height
c.getContext('2d').drawImage(bmp, 0, 0)
if (typeof bmp.close === 'function') bmp.close()
const out = await new Promise(res => c.toBlob(b => res(b), 'image/png'))
c.width = 0
c.height = 0
if (out) return out
}
} catch (e) { /* 走 img 回退 */ }
return await new Promise((resolve) => {
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = () => {
const c = document.createElement('canvas')
c.width = img.naturalWidth
c.height = img.naturalHeight
c.getContext('2d').drawImage(img, 0, 0)
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
c.toBlob(b => resolve(b || blob), 'image/png')
}
img.onerror = () => {
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
resolve(blob)
}
img.src = url
})
}
/**
* 复制到系统剪贴板:运营场景最常用的一条路 —— 复制后直接粘进聊天窗口/小红书后台,
* 省掉「下载 → 再上传」。必须在用户手势里调用(浏览器要求),失败给可操作提示。
*/
export async function copyBlobToClipboard(blob) {
const nav = typeof navigator !== 'undefined' ? navigator : null
const CI = typeof window !== 'undefined' ? window.ClipboardItem : null
if (!nav || !nav.clipboard || typeof nav.clipboard.write !== 'function' || typeof CI !== 'function') {
toast('当前浏览器不支持复制图片,请用「导出」下载', 'warn')
return false
}
let png = blob
if (blob.type !== 'image/png') {
try { png = await toPngBlob(blob) } catch (e) { png = blob }
}
try {
await nav.clipboard.write([new CI({ 'image/png': png })])
toast('已复制到剪贴板(' + Math.round(png.size / 1024) + 'KB),可直接粘贴', 'success')
return true
} catch (e) {
toast('复制失败:' + ((e && e.message) || '浏览器拒绝了剪贴板写入') + ';可用「导出」下载', 'error')
return false
}
}
+40 -5
View File
@@ -30,14 +30,15 @@ import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotSta
import { cancelImagePlacement } from './placement.js' import { cancelImagePlacement } from './placement.js'
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js' import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
import { createEl, loadImage } from './dom.js' import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput } from './objects.js' import { renderObjects, hideTextInput, textBounds } from './objects.js'
import { setupCanvas } from './viewport.js' import { setupCanvas } from './viewport.js'
import { resetOverlayTransform } from './scale.js' import { resetOverlayTransform } from './scale.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js' import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js' import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js' import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { renderFxPanel } from './effects.js' import { renderFxPanel } from './effects.js'
import { loadExportOptions, prepareOutput, downloadBlob, bindExportUI, renderExportUI } from './export.js' import { loadExportOptions, prepareOutput, downloadBlob, copyBlobToClipboard, bindExportUI, renderExportUI } from './export.js'
import { loadRecentColors } from './recent-colors.js'
import { toast } from './commands.js' import { toast } from './commands.js'
// ============ 打开编辑器 ============ // ============ 打开编辑器 ============
@@ -63,6 +64,7 @@ import { toast } from './commands.js'
updateAllUI() updateAllUI()
registerSelectionCommands() registerSelectionCommands()
loadExportOptions() loadExportOptions()
loadRecentColors()
bindLiteUI() bindLiteUI()
bindFloating() bindFloating()
bindExportUI() bindExportUI()
@@ -274,6 +276,19 @@ import { toast } from './commands.js'
} }
} }
/** 复制当前结果为图片到系统剪贴板:不关编辑器、不写宿主节点 */
export async function copyResult() {
if (S.placingImage) cancelImagePlacement()
try {
const { blob } = await prepareOutput()
await copyBlobToClipboard(blob)
if (S.renderAll) S.renderAll() // 摘要里的「上次输出 …KB」要跟上
} catch (e) {
console.error('[IWB编辑器] 复制失败:', e)
toast('复制失败:' + ((e && e.message) || '图片可能跨域'), 'error')
}
}
// ============ 暴露接口 ============ // ============ 暴露接口 ============
/** /**
* 快照/历史开销观测口(性能回归与手测用): * 快照/历史开销观测口(性能回归与手测用):
@@ -308,9 +323,29 @@ import { toast } from './commands.js'
opacity: l.opacity == null ? 1 : l.opacity, opacity: l.opacity == null ? 1 : l.opacity,
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null
})), })),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color })), shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })), texts: S.textLayers.map(t => ({
selectedShapeId: S.selectedShapeId, id: t.id, text: t.text, x: t.x, y: t.y, fontSize: t.fontSize, color: t.color,
fontWeight: t.fontWeight, align: t.align, lineHeight: t.lineHeight,
strokeWidth: t.strokeWidth, strokeColor: t.strokeColor, bgFill: !!t.bgFill, bgColor: t.bgColor,
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
box: (() => { const b = textBounds(t); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) } })()
})),
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
guides: S.guides ? S.guides.map(g => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
recentColors: (S.recentColors || []).slice(),
textDefaults: {
weight: S.textWeight, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}, selectedShapeId: S.selectedShapeId,
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
drag: S.shapeDrag ? ('shape:' + S.shapeDrag.mode + (S.shapeDrag.handle ? ':' + S.shapeDrag.handle : ''))
: S.textDrag ? ('text:' + S.textDrag.mode)
: S.bitmapDrag ? ('bitmap:' + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ':' + S.bitmapDrag.handle : ''))
: null,
selectedTextId: S.selectedTextId, selectedTextId: S.selectedTextId,
penEditId: S.penEditId, penEditId: S.penEditId,
activeLayerId: S.activeLayerId, activeLayerId: S.activeLayerId,
+19 -18
View File
@@ -8,7 +8,9 @@
'use strict' 'use strict'
import { S, runtime } from './state.js' import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js' import { allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, otherObjectBoxes, renderObjects, selectUnit, sortLayersByZ } from './objects.js'
import { drawTextObject } from './text.js'
import { snapMove } from './snap.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js' import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js' import { viewScale } from './scale.js'
import { drawShape } from './tools.js' import { drawShape } from './tools.js'
@@ -276,8 +278,19 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
if (!drag || !layer) return if (!drag || !layer) return
const base = drag.layer const base = drag.layer
if (drag.mode === 'move') { if (drag.mode === 'move') {
layer.x = base.x + pos.x - drag.start.x let nx = base.x + pos.x - drag.start.x
layer.y = base.y + pos.y - drag.start.y let ny = base.y + pos.y - drag.start.y
// 吸附到画布中线/边界与其它元素(按住 Alt 临时关掉)
if (!S._altDown && base.w > 0 && base.h > 0) {
const s = snapMove({ x: nx, y: ny, w: base.w, h: base.h }, otherObjectBoxes(layer))
nx += s.dx
ny += s.dy
S.guides = s.guides.length ? s.guides : null
} else {
S.guides = null
}
layer.x = nx
layer.y = ny
if (isDrawableLayer(layer)) layer._bounds = undefined if (isDrawableLayer(layer)) layer._bounds = undefined
} else if (drag.mode === 'rotate') { } else if (drag.mode === 'rotate') {
const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2 const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2
@@ -454,21 +467,9 @@ export function setActiveLayer(id) {
if (kind === 'shape') { if (kind === 'shape') {
drawShape(ctx, obj) drawShape(ctx, obj)
} else { } else {
ctx.save() // 文字绘制统一走 text.js:预览、落层、缩略图必须是同一套度量与画法,
ctx.textBaseline = 'top' // 否则「量出来的选中框」和「画出来的字」会各说各话(多行/描边/底色尤其明显)
ctx.globalAlpha = obj.opacity != null ? obj.opacity : 1 drawTextObject(ctx, obj)
const rot = obj.rotation || 0
if (rot) {
const b = textBounds(obj)
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
ctx.translate(cx, cy)
ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
}
ctx.font = TEXT_FONT(obj.fontSize)
ctx.fillStyle = obj.color
ctx.fillText(obj.text, obj.x, obj.y)
ctx.restore()
} }
} }
+47 -11
View File
@@ -16,19 +16,19 @@ import { drawShape, setTool } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js' import { saveSnapshot, snapshotState } from './history.js'
import { toast } from './commands.js' import { toast } from './commands.js'
import { renderOptionBar, updateLayerUI } from './events.js' import { renderOptionBar, updateLayerUI } from './events.js'
import { fontOf, newTextStyle, textBox } from './text.js'
import { drawGuides } from './snap.js'
import { isDrawableLayer } from '../vendor/layer-logic.js' import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============ // ============ 文字图层 ============
export const TEXT_FONT = (size) => 'bold ' + size + 'px sans-serif' /** 兼容旧调用点:TEXT_FONT(size) 返回粗体字体串;带样式的字体请用 text.js 的 fontOf(obj) */
export const TEXT_FONT = (size) => fontOf({ fontSize: size, fontWeight: 'bold' })
/** 文字包围盒:含多行、底色 padding 与描边外扩(单行时与旧实现完全一致) */
export function textBounds(t) { export function textBounds(t) {
const ctx = S.textCtx return textBox(t)
ctx.font = TEXT_FONT(t.fontSize)
const w = ctx.measureText(t.text).width
const h = t.fontSize * 1.25
return { x: t.x, y: t.y, w, h }
} }
export function getSelectedText() { export function getSelectedText() {
@@ -204,6 +204,23 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
return null return null
} }
/** 其它可见元素的包围盒(拖动吸附用):排除自己与原图底图(底图边界=画布边界,重复) */
export function otherObjectBoxes(exclude) {
const out = []
for (const unit of layerUnits()) {
const o = unit.obj
if (!o || o === exclude || o.id === 'base' || o.visible === false) continue
if (unit.kind === 'bitmap') {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h })
} else if (unit.kind === 'text') {
out.push(textBox(o))
} else {
out.push(shapeBounds(o))
}
}
return out
}
export function hitAnyObject(pos) { export function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) { for (const unit of layerUnitsDesc()) {
if (unit.kind === 'bitmap') continue if (unit.kind === 'bitmap') continue
@@ -439,6 +456,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj) for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj)
reorderLayerCanvas() reorderLayerCanvas()
clearOverlay() clearOverlay()
// 吸附参考线:拖动中才有值,松手清空。画在 overlay 层,不参与合成与导出
drawGuides(S.overlayCtx, S.guides)
if (tempShape) drawShape(S.overlayCtx, tempShape) if (tempShape) drawShape(S.overlayCtx, tempShape)
if (S.tool === 'pen' && S.penPath && S.penPath.pts.length) drawPenPathPreview() if (S.tool === 'pen' && S.penPath && S.penPath.pts.length) drawPenPathPreview()
// 图片放置模式优先显示放置预览 // 图片放置模式优先显示放置预览
@@ -570,12 +589,20 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字输入框 ============ // ============ 文字输入框 ============
export function showTextInput(x, y, layer) { export function showTextInput(x, y, layer) {
const input = runtime.el.querySelector('.iwb-editor-text-input') const input = runtime.el.querySelector('.iwb-editor-text-input')
const rect = S.canvasStack.getBoundingClientRect()
const wrapRect = S.canvasWrap.getBoundingClientRect() const wrapRect = S.canvasWrap.getBoundingClientRect()
const sx = rect.width / S.imgW // 不能用 canvasStack 的矩形换算:stack 的尺寸是 (imgW + 2*overlayPad) * scale,
const sy = rect.height / S.imgH // 图片在 stack 内部还额外偏移了 pad*scale(图层 canvas 的 left/top)。
input.style.left = (rect.left - wrapRect.left + x * sx) + 'px' // 拿它算比例会偏小、又漏掉这段偏移,输入框就整体跑到点击点的左上方。
input.style.top = (rect.top - wrapRect.top + y * sy) + 'px' // textCanvas 与图层 canvas 同基准,矩形精确等于「图片显示区域」。
const box = (S.textCanvas || S.canvasStack).getBoundingClientRect()
const sx = S.imgW ? box.width / S.imgW : 1
const sy = S.imgH ? box.height / S.imgH : 1
// textarea 有 2px 边框 + 8/4px 内边距,反向抵消后「输入框里的字起点」正压在点击点上,
// 与提交后 drawTextObject 从 t.x/t.y 起画的位置完全一致(所见即所得)。
const INSET_X = 10
const INSET_Y = 6
input.style.left = (box.left - wrapRect.left + x * sx - INSET_X) + 'px'
input.style.top = (box.top - wrapRect.top + y * sy - INSET_Y) + 'px'
input.style.display = 'block' input.style.display = 'block'
if (layer) { if (layer) {
input.value = layer.text input.value = layer.text
@@ -588,6 +615,9 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
input.select() input.select()
input.dataset.x = x input.dataset.x = x
input.dataset.y = y input.dataset.y = y
// textarea 不会自己长高:先按内容撑开,否则多行文本会挤在一行里
input.style.height = 'auto'
input.style.height = Math.max(30, input.scrollHeight + 4) + 'px'
} }
export function hideTextInput() { export function hideTextInput() {
@@ -632,6 +662,12 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
x, y, text, x, y, text,
color: S.color, color: S.color,
fontSize: Math.max(8, S.textSize), fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}),
opacity: 1, opacity: 1,
visible: true, visible: true,
locked: false, locked: false,
@@ -0,0 +1,54 @@
/* recent-colors.js - 最近使用颜色(v1.9)
*
* 只依赖 state.js(叶子模块):tools.js 在改色时调用 rememberColor(),
* color pop 打开时 renderRecentColors() 把最近 8 个色块铺出来。
* 持久化走宿主 ctx.settings(小 KV,不放像素,符合宿主存储约定)。
*/
'use strict'
import { S, runtime } from './state.js'
const MAX = 8
const KEY = 'recentColors'
function valid(hex) {
return /^#[0-9a-f]{6}$/i.test(String(hex || ''))
}
export function loadRecentColors() {
const st = S.callbacks && S.callbacks.settings
let list = []
if (st && typeof st.get === 'function') {
try {
const got = st.get(KEY)
if (Array.isArray(got)) list = got
} catch (e) { /* 宿主 KV 不可用就当没有 */ }
}
S.recentColors = list.filter(valid).map(c => String(c).toLowerCase()).slice(0, MAX)
renderRecentColors()
}
/** 记一个颜色:去重后置顶,最多 8 个 */
export function rememberColor(hex) {
if (!valid(hex)) return
const c = String(hex).toLowerCase()
if (S.recentColors && S.recentColors[0] === c) return // 已经是最新,别每次重排
const list = [c].concat((S.recentColors || []).filter(x => x !== c))
S.recentColors = list.slice(0, MAX)
const st = S.callbacks && S.callbacks.settings
if (st && typeof st.set === 'function') {
try { st.set(KEY, S.recentColors) } catch (e) { /* 存不下就只在本次会话用 */ }
}
renderRecentColors()
}
export function renderRecentColors() {
const wrap = runtime.el && runtime.el.querySelector('.iwb-editor-recent-colors')
if (!wrap) return
const list = S.recentColors || []
wrap.innerHTML = list.map(c =>
`<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`
).join('')
wrap.hidden = !list.length
}
+94
View File
@@ -0,0 +1,94 @@
/* snap.js - 拖动吸附与参考线(v1.9)
*
* 只做两件事:算「要不要吸、吸多少」,以及把参考线画出来。
* 不碰对象的写入 —— 调用方拿到 dx/dy 自己应用到 x/y,再在 render 里画线。
* 这样位图、文字、形状三种拖动可以共用同一套吸附,不会各写一遍阈值。
*
* 吸附目标:画布中线/四边 + 其它可见元素的左/中/右与上/中/下。
* 阈值按屏幕像素给(6px),换算成图片像素后再比较 —— 否则放大图片时
* 吸附范围会跟着放大到几十像素,鼠标还没靠近就被拽走。
*/
'use strict'
import { S } from './state.js'
import { viewScale } from './scale.js'
/** 吸附触发距离(屏幕像素) */
export const SNAP_SCREEN_PX = 6
/** 参考线颜色:洋红,和选中框的橙色区分开 */
const GUIDE_COLOR = '#ff2d95'
function pushBox(targets, box) {
const x2 = box.x + box.w
const y2 = box.y + box.h
targets.x.push(box.x, box.x + box.w / 2, x2)
targets.y.push(box.y, box.y + box.h / 2, y2)
}
/** 在候选线里找「离得最近且不超过阈值」的那条,返回需要平移的量 */
function nearest(targets, sources, tol, axis) {
let best = null
for (let i = 0; i < targets.length; i++) {
for (let j = 0; j < sources.length; j++) {
const delta = targets[i] - sources[j]
const abs = Math.abs(delta)
if (abs > tol) continue
if (!best || abs < Math.abs(best.delta)) best = { delta: delta, at: targets[i], axis: axis }
}
}
return best
}
/**
* 计算吸附位移。
* @param {{x:number,y:number,w:number,h:number}} box 被拖元素的包围盒(已按指针位移算好,未吸附)
* @param {Array<{x:number,y:number,w:number,h:number}>} others 其它元素的包围盒
* @returns {{dx:number, dy:number, guides:Array}}
*/
export function snapMove(box, others) {
const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale())
const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] }
for (const o of others || []) {
if (!o || !isFinite(o.x) || !isFinite(o.y)) continue
pushBox(targets, o)
}
const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w]
const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h]
const gx = nearest(targets.x, sourcesX, tol, 'x')
const gy = nearest(targets.y, sourcesY, tol, 'y')
const guides = []
if (gx) guides.push(gx)
if (gy) guides.push(gy)
return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides: guides }
}
/** 画参考线(贯穿整个画布 + overlay 外扩区,拖动时一眼看到对齐到哪) */
export function drawGuides(ctx, guides) {
if (!guides || !guides.length || !ctx) return
const scale = viewScale()
const pad = S.overlayPad || 0
ctx.save()
ctx.strokeStyle = GUIDE_COLOR
ctx.lineWidth = 1 / Math.max(0.02, scale)
ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)])
for (const g of guides) {
ctx.beginPath()
if (g.axis === 'x') {
ctx.moveTo(g.at, -pad)
ctx.lineTo(g.at, S.imgH + pad)
} else {
ctx.moveTo(-pad, g.at)
ctx.lineTo(S.imgW + pad, g.at)
}
ctx.stroke()
}
ctx.setLineDash([])
ctx.restore()
}
export function clearGuides() {
if (!S.guides) return
S.guides = null
}
+12
View File
@@ -38,7 +38,18 @@
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细, // v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。 // 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细 shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
shapeRadius: 0, // 矩形圆角半径 px(v1.9,仅 rect 有意义)
textSize: 32, // 新建文字的字号 px textSize: 32, // 新建文字的字号 px
// ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ----
textWeight: 'bold', // bold | normal | 900
textAlign: 'left', // left | center | right(多行时各行按块宽对齐)
textLineHeight: 1.25, // 行高倍数(1.25 = 老版单行高度,勿随意改)
textStrokeWidth: 0, // 描边宽度 px,0 = 无描边
textStrokeColor: '#ffffff',
textBgFill: false, // 底色块
textBgColor: '#000000',
// 最近使用颜色(最多 8 个,存 ctx.settings,跨会话保留)
recentColors: [],
// 图层系统 // 图层系统
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }] layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标) activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标)
@@ -113,6 +124,7 @@
exportOptions: null, // { preset, format, bg, maxKB, size },来自 ctx.settings exportOptions: null, // { preset, format, bg, maxKB, size },来自 ctx.settings
interaction: 'idle', // 轻量交互状态机:idle | marquee | lasso | placing | cropping interaction: 'idle', // 轻量交互状态机:idle | marquee | lasso | placing | cropping
renderAll: null, // 由 index.js 注入的统一重绘出口 renderAll: null, // 由 index.js 注入的统一重绘出口
guides: null, // 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}]
lastExport: null // 观测口:{ bytes, width, height, format, preset } lastExport: null // 观测口:{ bytes, width, height, format, preset }
} }
+157
View File
@@ -0,0 +1,157 @@
/* text.js - 文字的字体串、度量与绘制(v1.9)
*
* 为什么单独一个模块:文字要在两处画 —— 落层(layers.js#drawVectorToCanvas)与
* 预览/度量(objects.js)。两边各写一遍必然出现「量出来的框和画出来的字不一样」。
* 这里做成零依赖叶子模块(不 import 任何编辑器模块),objects.js 与 layers.js
* 都只往下依赖它,不会形成循环 import(esbuild 打成 IIFE 时循环 import 会拿到 undefined)。
*
* 坐标语义(与 v1.8 之前保持一致,勿随意改动):
* t.x / t.y 是「文字块」左上角;底色 padding 与描边从这一点向内/外扩展。
* 单行 + 无底色 + 无描边时,textBox() 与老版 textBounds() 完全相等(w=文字宽,h=fontSize×1.25)。
*/
'use strict'
/** 默认行高倍数:必须等于老版的 fontSize×1.25,否则单行文字的选中框会变高 */
export const TEXT_LINE_HEIGHT = 1.25
/** 底色块相对字号的 padding 系数 */
const BG_PAD_RATIO = 0.3
let _measureCtx = null
/** 度量用的离屏 ctx:不依赖编辑器 DOM 是否已建好,避免 textBounds 在早期调用时抛错 */
function measureCtx() {
if (!_measureCtx) {
const c = document.createElement('canvas')
c.width = 8
c.height = 8
_measureCtx = c.getContext('2d')
}
return _measureCtx
}
/** 字重:'bold' | 'normal' | '900' …(默认粗体,与老版一致) */
export function weightOf(t) {
const w = t && t.fontWeight
return w == null || w === '' ? 'bold' : String(w)
}
export function fontOf(t) {
const size = Math.max(4, Number(t && t.fontSize) || 32)
return weightOf(t) + ' ' + size + 'px sans-serif'
}
/** 文字的排布度量:分行、每行宽度、行高、底色 padding、描边宽度 */
export function textMetrics(t) {
const ctx = measureCtx()
const font = fontOf(t)
ctx.font = font
const raw = (t && t.text) == null ? '' : String(t.text)
const lines = raw.split('\n')
const widths = lines.map(line => ctx.measureText(line).width)
const size = Math.max(4, Number(t && t.fontSize) || 32)
const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT)
const w = lines.length ? Math.max.apply(null, widths) : 0
const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0
const sw = Math.max(0, Number(t && t.strokeWidth) || 0)
return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size }
}
/** 包围盒(图片坐标):含底色 padding 与描边向外扩出的一半 */
export function textBox(t) {
const m = textMetrics(t)
const half = m.sw / 2
return {
x: t.x - half,
y: t.y - half,
w: Math.max(m.w, 2) + m.pad * 2 + m.sw,
h: Math.max(m.h, 1) + m.pad * 2 + m.sw
}
}
function alignOf(t) {
const a = t && t.align
return a === 'center' || a === 'right' ? a : 'left'
}
/**
* 画一段文字(含底色块、描边、多行、旋转)。
* 底色块与描边都按「块」来画:底色覆盖整块,描边沿字形外沿。
*/
export function drawTextObject(ctx, t) {
const m = textMetrics(t)
ctx.save()
ctx.textBaseline = 'top'
ctx.globalAlpha = t.opacity != null ? t.opacity : 1
const b = textBox(t)
const rot = t.rotation || 0
if (rot) {
const cx = b.x + b.w / 2
const cy = b.y + b.h / 2
ctx.translate(cx, cy)
ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
}
ctx.font = m.font
const align = alignOf(t)
const boxW = m.w + m.pad * 2
// 底色块:先于文字画,圆角按字号比例给一点(纯直角贴小字会很硬)
if (t.bgFill) {
const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2)
// 0.55 在浅色/花色底图上偏透,用户容易以为「底色没生效」;0.68 既压得住底图,
// 也还看得见一点背景,是「垫一块板让字立起来」的常用手感。
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? 0.68 : t.bgAlpha)
ctx.fillStyle = t.bgColor || '#000000'
const bx = t.x, by = t.y
const bw = boxW, bh = m.h + m.pad * 2
ctx.beginPath()
if (typeof ctx.roundRect === 'function') {
ctx.roundRect(bx, by, bw, bh, r)
} else {
ctx.moveTo(bx + r, by)
ctx.arcTo(bx + bw, by, bx + bw, by + bh, r)
ctx.arcTo(bx + bw, by + bh, bx, by + bh, r)
ctx.arcTo(bx, by + bh, bx, by, r)
ctx.arcTo(bx, by, bx + bw, by, r)
ctx.closePath()
}
ctx.fill()
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1)
}
// 对齐以「块内可用宽度(不含 padding)」为基准:多行时各行按这个宽度对齐
ctx.textAlign = align
const left = t.x + m.pad
const ox = align === 'center' ? left + m.w / 2 : align === 'right' ? left + m.w : left
ctx.lineJoin = 'round'
ctx.miterLimit = 2
for (let i = 0; i < m.lines.length; i++) {
const y = t.y + m.pad + i * m.lh
if (m.sw > 0) {
ctx.lineWidth = m.sw
ctx.strokeStyle = t.strokeColor || '#ffffff'
ctx.strokeText(m.lines[i], ox, y)
}
ctx.fillStyle = t.color || '#ff4444'
ctx.fillText(m.lines[i], ox, y)
}
ctx.restore()
}
/** 从默认样式造一段文字的字段(新建文字 / 老对象补默认值共用) */
export function newTextStyle(src) {
const s = src || {}
return {
fontWeight: weightOf(s),
align: alignOf(s),
lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT,
strokeWidth: Math.max(0, Number(s.strokeWidth) || 0),
strokeColor: s.strokeColor || '#ffffff',
bgFill: !!s.bgFill,
bgColor: s.bgColor || '#000000',
bgAlpha: s.bgAlpha == null ? 0.68 : Number(s.bgAlpha)
}
}
+30
View File
@@ -18,6 +18,7 @@ import { saveSnapshot } from './history.js'
import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js' import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js' import { isDrawableLayer } from '../vendor/layer-logic.js'
import { hexToRgb, rgbToHex } from '../vendor/image-math.js' import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
import { rememberColor } from './recent-colors.js'
// ============ 绘制工具 ============ // ============ 绘制工具 ============
@@ -160,6 +161,24 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
S.pickerComposite = null S.pickerComposite = null
} }
/** 圆角半径:夹在短边一半以内,避免圆角把矩形吃掉变胶囊/消失 */
function roundedRadius(s, w, h) {
const r = Number(s && s.radius) || 0
if (r <= 0) return 0
return Math.min(r, Math.min(w, h) / 2)
}
/** 圆角矩形路径:不用 ctx.roundRect(老浏览器没有),手写 arcs,行为可控 */
function roundRectPath(ctx, x, y, w, h, r) {
const rr = Math.min(r, Math.min(w, h) / 2)
ctx.moveTo(x + rr, y)
ctx.arcTo(x + w, y, x + w, y + h, rr)
ctx.arcTo(x + w, y + h, x, y + h, rr)
ctx.arcTo(x, y + h, x, y, rr)
ctx.arcTo(x, y, x + w, y, rr)
ctx.closePath()
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */ /** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
export function drawShape(ctx, s) { export function drawShape(ctx, s) {
ctx.save() ctx.save()
@@ -181,8 +200,16 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
if (pts.length > 1) { ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y); if (s.closed) ctx.closePath(); if (s.closed && s.fill) { ctx.fillStyle = s.color; ctx.fill() } ctx.stroke() } if (pts.length > 1) { ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y); if (s.closed) ctx.closePath(); if (s.closed && s.fill) { ctx.fillStyle = s.color; ctx.fill() } ctx.stroke() }
} else if (s.type === 'rect') { } else if (s.type === 'rect') {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1) const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
const radius = roundedRadius(s, rw, rh)
if (radius > 0) {
ctx.beginPath()
roundRectPath(ctx, rx, ry, rw, rh, radius)
if (s.fill) { ctx.fillStyle = s.color; ctx.fill() }
ctx.stroke()
} else {
if (s.fill) { ctx.fillStyle = s.color; ctx.fillRect(rx, ry, rw, rh) } if (s.fill) { ctx.fillStyle = s.color; ctx.fillRect(rx, ry, rw, rh) }
ctx.strokeRect(rx, ry, rw, rh) ctx.strokeRect(rx, ry, rw, rh)
}
} else if (s.type === 'circle') { } else if (s.type === 'circle') {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2) const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2)
const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1) const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
@@ -380,6 +407,9 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
export function applyColorChange(color, opts) { export function applyColorChange(color, opts) {
const skipHistory = !!(opts && opts.skipHistory) const skipHistory = !!(opts && opts.skipHistory)
S.color = color S.color = color
// 只有「确认型」改色才进最近使用:拖 SV 时 skipHistory=true 每帧都调,
// 全记进去会把最近色刷成一串相邻色,毫无用处。
if (!skipHistory) rememberColor(color)
updateColorUI() updateColorUI()
const t = getSelectedText() const t = getSelectedText()
if (t && !t.locked && t.color !== S.color) { if (t && !t.locked && t.color !== S.color) {
+618 -50
View File
@@ -9,7 +9,7 @@
var __IWB_ANNOTATE_MANIFEST__ = { var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate', id: 'image-annotate',
name: '标注 / 修图', name: '标注 / 修图',
version: '1.8.3', version: '1.9.1',
apiVersion: 1, apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'], capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: { settings: {
@@ -63,8 +63,25 @@ var __IWB_ANNOTATE_MANIFEST__ = {
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。 // 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, shapeLineWidth: 3,
// 矩形/圆形/箭头/钢笔的描边粗细 // 矩形/圆形/箭头/钢笔的描边粗细
shapeRadius: 0,
// 矩形圆角半径 px(v1.9,仅 rect 有意义)
textSize: 32, textSize: 32,
// 新建文字的字号 px // 新建文字的字号 px
// ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ----
textWeight: "bold",
// bold | normal | 900
textAlign: "left",
// left | center | right(多行时各行按块宽对齐)
textLineHeight: 1.25,
// 行高倍数(1.25 = 老版单行高度,勿随意改)
textStrokeWidth: 0,
// 描边宽度 px,0 = 无描边
textStrokeColor: "#ffffff",
textBgFill: false,
// 底色块
textBgColor: "#000000",
// 最近使用颜色(最多 8 个,存 ctx.settings,跨会话保留)
recentColors: [],
// 图层系统 // 图层系统
layers: [], layers: [],
// 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }] // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
@@ -171,6 +188,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
// 轻量交互状态机:idle | marquee | lasso | placing | cropping // 轻量交互状态机:idle | marquee | lasso | placing | cropping
renderAll: null, renderAll: null,
// 由 index.js 注入的统一重绘出口 // 由 index.js 注入的统一重绘出口
guides: null,
// 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}]
lastExport: null lastExport: null
// 观测口:{ bytes, width, height, format, preset } // 观测口:{ bytes, width, height, format, preset }
}; };
@@ -461,6 +480,50 @@ var __IWB_ANNOTATE_MANIFEST__ = {
return 0; return 0;
} }
// image-annotate/plugin/editor/recent-colors.js
var MAX = 8;
var KEY = "recentColors";
function valid(hex) {
return /^#[0-9a-f]{6}$/i.test(String(hex || ""));
}
function loadRecentColors() {
const st = S.callbacks && S.callbacks.settings;
let list = [];
if (st && typeof st.get === "function") {
try {
const got = st.get(KEY);
if (Array.isArray(got)) list = got;
} catch (e) {
}
}
S.recentColors = list.filter(valid).map((c) => String(c).toLowerCase()).slice(0, MAX);
renderRecentColors();
}
function rememberColor(hex) {
if (!valid(hex)) return;
const c = String(hex).toLowerCase();
if (S.recentColors && S.recentColors[0] === c) return;
const list = [c].concat((S.recentColors || []).filter((x) => x !== c));
S.recentColors = list.slice(0, MAX);
const st = S.callbacks && S.callbacks.settings;
if (st && typeof st.set === "function") {
try {
st.set(KEY, S.recentColors);
} catch (e) {
}
}
renderRecentColors();
}
function renderRecentColors() {
const wrap = runtime.el && runtime.el.querySelector(".iwb-editor-recent-colors");
if (!wrap) return;
const list = S.recentColors || [];
wrap.innerHTML = list.map(
(c) => `<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`
).join("");
wrap.hidden = !list.length;
}
// image-annotate/plugin/editor/tools.js // image-annotate/plugin/editor/tools.js
var brushStampCache = { key: "", canvas: null }; var brushStampCache = { key: "", canvas: null };
function getBrushStamp(size, color, hardness) { function getBrushStamp(size, color, hardness) {
@@ -585,6 +648,20 @@ var __IWB_ANNOTATE_MANIFEST__ = {
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH); S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH);
S.pickerComposite = null; S.pickerComposite = null;
} }
function roundedRadius(s, w, h) {
const r = Number(s && s.radius) || 0;
if (r <= 0) return 0;
return Math.min(r, Math.min(w, h) / 2);
}
function roundRectPath(ctx, x, y, w, h, r) {
const rr = Math.min(r, Math.min(w, h) / 2);
ctx.moveTo(x + rr, y);
ctx.arcTo(x + w, y, x + w, y + h, rr);
ctx.arcTo(x + w, y + h, x, y + h, rr);
ctx.arcTo(x, y + h, x, y, rr);
ctx.arcTo(x, y, x + w, y, rr);
ctx.closePath();
}
function drawShape(ctx, s) { function drawShape(ctx, s) {
ctx.save(); ctx.save();
ctx.globalAlpha = s.opacity != null ? s.opacity : 1; ctx.globalAlpha = s.opacity != null ? s.opacity : 1;
@@ -615,11 +692,22 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
} else if (s.type === "rect") { } else if (s.type === "rect") {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1); const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1);
const radius = roundedRadius(s, rw, rh);
if (radius > 0) {
ctx.beginPath();
roundRectPath(ctx, rx, ry, rw, rh, radius);
if (s.fill) {
ctx.fillStyle = s.color;
ctx.fill();
}
ctx.stroke();
} else {
if (s.fill) { if (s.fill) {
ctx.fillStyle = s.color; ctx.fillStyle = s.color;
ctx.fillRect(rx, ry, rw, rh); ctx.fillRect(rx, ry, rw, rh);
} }
ctx.strokeRect(rx, ry, rw, rh); ctx.strokeRect(rx, ry, rw, rh);
}
} else if (s.type === "circle") { } else if (s.type === "circle") {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2); const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2);
const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1); const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1);
@@ -780,6 +868,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function applyColorChange(color, opts) { function applyColorChange(color, opts) {
const skipHistory = !!(opts && opts.skipHistory); const skipHistory = !!(opts && opts.skipHistory);
S.color = color; S.color = color;
if (!skipHistory) rememberColor(color);
updateColorUI(); updateColorUI();
const t = getSelectedText(); const t = getSelectedText();
if (t && !t.locked && t.color !== S.color) { if (t && !t.locked && t.color !== S.color) {
@@ -901,14 +990,186 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}, 2600); }, 2600);
} }
// image-annotate/plugin/editor/text.js
var TEXT_LINE_HEIGHT = 1.25;
var BG_PAD_RATIO = 0.3;
var _measureCtx = null;
function measureCtx() {
if (!_measureCtx) {
const c = document.createElement("canvas");
c.width = 8;
c.height = 8;
_measureCtx = c.getContext("2d");
}
return _measureCtx;
}
function weightOf(t) {
const w = t && t.fontWeight;
return w == null || w === "" ? "bold" : String(w);
}
function fontOf(t) {
const size = Math.max(4, Number(t && t.fontSize) || 32);
return weightOf(t) + " " + size + "px sans-serif";
}
function textMetrics(t) {
const ctx = measureCtx();
const font = fontOf(t);
ctx.font = font;
const raw = (t && t.text) == null ? "" : String(t.text);
const lines = raw.split("\n");
const widths = lines.map((line) => ctx.measureText(line).width);
const size = Math.max(4, Number(t && t.fontSize) || 32);
const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT);
const w = lines.length ? Math.max.apply(null, widths) : 0;
const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0;
const sw = Math.max(0, Number(t && t.strokeWidth) || 0);
return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size };
}
function textBox(t) {
const m = textMetrics(t);
const half = m.sw / 2;
return {
x: t.x - half,
y: t.y - half,
w: Math.max(m.w, 2) + m.pad * 2 + m.sw,
h: Math.max(m.h, 1) + m.pad * 2 + m.sw
};
}
function alignOf(t) {
const a = t && t.align;
return a === "center" || a === "right" ? a : "left";
}
function drawTextObject(ctx, t) {
const m = textMetrics(t);
ctx.save();
ctx.textBaseline = "top";
ctx.globalAlpha = t.opacity != null ? t.opacity : 1;
const b = textBox(t);
const rot = t.rotation || 0;
if (rot) {
const cx = b.x + b.w / 2;
const cy = b.y + b.h / 2;
ctx.translate(cx, cy);
ctx.rotate(rot * Math.PI / 180);
ctx.translate(-cx, -cy);
}
ctx.font = m.font;
const align = alignOf(t);
const boxW = m.w + m.pad * 2;
if (t.bgFill) {
const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2);
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? 0.68 : t.bgAlpha);
ctx.fillStyle = t.bgColor || "#000000";
const bx = t.x, by = t.y;
const bw = boxW, bh = m.h + m.pad * 2;
ctx.beginPath();
if (typeof ctx.roundRect === "function") {
ctx.roundRect(bx, by, bw, bh, r);
} else {
ctx.moveTo(bx + r, by);
ctx.arcTo(bx + bw, by, bx + bw, by + bh, r);
ctx.arcTo(bx + bw, by + bh, bx, by + bh, r);
ctx.arcTo(bx, by + bh, bx, by, r);
ctx.arcTo(bx, by, bx + bw, by, r);
ctx.closePath();
}
ctx.fill();
ctx.globalAlpha = t.opacity != null ? t.opacity : 1;
}
ctx.textAlign = align;
const left = t.x + m.pad;
const ox = align === "center" ? left + m.w / 2 : align === "right" ? left + m.w : left;
ctx.lineJoin = "round";
ctx.miterLimit = 2;
for (let i = 0; i < m.lines.length; i++) {
const y = t.y + m.pad + i * m.lh;
if (m.sw > 0) {
ctx.lineWidth = m.sw;
ctx.strokeStyle = t.strokeColor || "#ffffff";
ctx.strokeText(m.lines[i], ox, y);
}
ctx.fillStyle = t.color || "#ff4444";
ctx.fillText(m.lines[i], ox, y);
}
ctx.restore();
}
function newTextStyle(src) {
const s = src || {};
return {
fontWeight: weightOf(s),
align: alignOf(s),
lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT,
strokeWidth: Math.max(0, Number(s.strokeWidth) || 0),
strokeColor: s.strokeColor || "#ffffff",
bgFill: !!s.bgFill,
bgColor: s.bgColor || "#000000",
bgAlpha: s.bgAlpha == null ? 0.68 : Number(s.bgAlpha)
};
}
// image-annotate/plugin/editor/snap.js
var SNAP_SCREEN_PX = 6;
var GUIDE_COLOR = "#ff2d95";
function pushBox(targets, box) {
const x2 = box.x + box.w;
const y2 = box.y + box.h;
targets.x.push(box.x, box.x + box.w / 2, x2);
targets.y.push(box.y, box.y + box.h / 2, y2);
}
function nearest(targets, sources, tol, axis) {
let best = null;
for (let i = 0; i < targets.length; i++) {
for (let j = 0; j < sources.length; j++) {
const delta = targets[i] - sources[j];
const abs = Math.abs(delta);
if (abs > tol) continue;
if (!best || abs < Math.abs(best.delta)) best = { delta, at: targets[i], axis };
}
}
return best;
}
function snapMove(box, others) {
const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale());
const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] };
for (const o of others || []) {
if (!o || !isFinite(o.x) || !isFinite(o.y)) continue;
pushBox(targets, o);
}
const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w];
const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h];
const gx = nearest(targets.x, sourcesX, tol, "x");
const gy = nearest(targets.y, sourcesY, tol, "y");
const guides = [];
if (gx) guides.push(gx);
if (gy) guides.push(gy);
return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides };
}
function drawGuides(ctx, guides) {
if (!guides || !guides.length || !ctx) return;
const scale = viewScale();
const pad = S.overlayPad || 0;
ctx.save();
ctx.strokeStyle = GUIDE_COLOR;
ctx.lineWidth = 1 / Math.max(0.02, scale);
ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)]);
for (const g of guides) {
ctx.beginPath();
if (g.axis === "x") {
ctx.moveTo(g.at, -pad);
ctx.lineTo(g.at, S.imgH + pad);
} else {
ctx.moveTo(-pad, g.at);
ctx.lineTo(S.imgW + pad, g.at);
}
ctx.stroke();
}
ctx.setLineDash([]);
ctx.restore();
}
// image-annotate/plugin/editor/objects.js // image-annotate/plugin/editor/objects.js
var TEXT_FONT = (size) => "bold " + size + "px sans-serif";
function textBounds(t) { function textBounds(t) {
const ctx = S.textCtx; return textBox(t);
ctx.font = TEXT_FONT(t.fontSize);
const w = ctx.measureText(t.text).width;
const h = t.fontSize * 1.25;
return { x: t.x, y: t.y, w, h };
} }
function getSelectedText() { function getSelectedText() {
return S.textLayers.find((t) => t.id === S.selectedTextId) || null; return S.textLayers.find((t) => t.id === S.selectedTextId) || null;
@@ -1066,6 +1327,21 @@ var __IWB_ANNOTATE_MANIFEST__ = {
for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit; for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit;
return null; return null;
} }
function otherObjectBoxes(exclude) {
const out = [];
for (const unit of layerUnits()) {
const o = unit.obj;
if (!o || o === exclude || o.id === "base" || o.visible === false) continue;
if (unit.kind === "bitmap") {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h });
} else if (unit.kind === "text") {
out.push(textBox(o));
} else {
out.push(shapeBounds(o));
}
}
return out;
}
function hitAnyObject(pos) { function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) { for (const unit of layerUnitsDesc()) {
if (unit.kind === "bitmap") continue; if (unit.kind === "bitmap") continue;
@@ -1307,6 +1583,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj); for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj);
reorderLayerCanvas(); reorderLayerCanvas();
clearOverlay(); clearOverlay();
drawGuides(S.overlayCtx, S.guides);
if (tempShape) drawShape(S.overlayCtx, tempShape); if (tempShape) drawShape(S.overlayCtx, tempShape);
if (S.tool === "pen" && S.penPath && S.penPath.pts.length) drawPenPathPreview(); if (S.tool === "pen" && S.penPath && S.penPath.pts.length) drawPenPathPreview();
if (S.placingImage) { if (S.placingImage) {
@@ -1431,12 +1708,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
function showTextInput(x, y, layer) { function showTextInput(x, y, layer) {
const input = runtime.el.querySelector(".iwb-editor-text-input"); const input = runtime.el.querySelector(".iwb-editor-text-input");
const rect = S.canvasStack.getBoundingClientRect();
const wrapRect = S.canvasWrap.getBoundingClientRect(); const wrapRect = S.canvasWrap.getBoundingClientRect();
const sx = rect.width / S.imgW; const box = (S.textCanvas || S.canvasStack).getBoundingClientRect();
const sy = rect.height / S.imgH; const sx = S.imgW ? box.width / S.imgW : 1;
input.style.left = rect.left - wrapRect.left + x * sx + "px"; const sy = S.imgH ? box.height / S.imgH : 1;
input.style.top = rect.top - wrapRect.top + y * sy + "px"; const INSET_X = 10;
const INSET_Y = 6;
input.style.left = box.left - wrapRect.left + x * sx - INSET_X + "px";
input.style.top = box.top - wrapRect.top + y * sy - INSET_Y + "px";
input.style.display = "block"; input.style.display = "block";
if (layer) { if (layer) {
input.value = layer.text; input.value = layer.text;
@@ -1449,6 +1728,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
input.select(); input.select();
input.dataset.x = x; input.dataset.x = x;
input.dataset.y = y; input.dataset.y = y;
input.style.height = "auto";
input.style.height = Math.max(30, input.scrollHeight + 4) + "px";
} }
function hideTextInput() { function hideTextInput() {
const input = runtime.el.querySelector(".iwb-editor-text-input"); const input = runtime.el.querySelector(".iwb-editor-text-input");
@@ -1493,6 +1774,16 @@ var __IWB_ANNOTATE_MANIFEST__ = {
text, text,
color: S.color, color: S.color,
fontSize: Math.max(8, S.textSize), fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight,
align: S.textAlign,
lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth,
strokeColor: S.textStrokeColor,
bgFill: S.textBgFill,
bgColor: S.textBgColor
}),
opacity: 1, opacity: 1,
visible: true, visible: true,
locked: false, locked: false,
@@ -1815,8 +2106,18 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (!drag || !layer) return; if (!drag || !layer) return;
const base = drag.layer; const base = drag.layer;
if (drag.mode === "move") { if (drag.mode === "move") {
layer.x = base.x + pos.x - drag.start.x; let nx = base.x + pos.x - drag.start.x;
layer.y = base.y + pos.y - drag.start.y; let ny = base.y + pos.y - drag.start.y;
if (!S._altDown && base.w > 0 && base.h > 0) {
const s = snapMove({ x: nx, y: ny, w: base.w, h: base.h }, otherObjectBoxes(layer));
nx += s.dx;
ny += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
layer.x = nx;
layer.y = ny;
if (isDrawableLayer(layer)) layer._bounds = void 0; if (isDrawableLayer(layer)) layer._bounds = void 0;
} else if (drag.mode === "rotate") { } else if (drag.mode === "rotate") {
const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2; const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2;
@@ -1983,21 +2284,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (kind === "shape") { if (kind === "shape") {
drawShape(ctx, obj); drawShape(ctx, obj);
} else { } else {
ctx.save(); drawTextObject(ctx, obj);
ctx.textBaseline = "top";
ctx.globalAlpha = obj.opacity != null ? obj.opacity : 1;
const rot = obj.rotation || 0;
if (rot) {
const b = textBounds(obj);
const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
ctx.translate(cx, cy);
ctx.rotate(rot * Math.PI / 180);
ctx.translate(-cx, -cy);
}
ctx.font = TEXT_FONT(obj.fontSize);
ctx.fillStyle = obj.color;
ctx.fillText(obj.text, obj.x, obj.y);
ctx.restore();
} }
} }
function toggleLayerVisibility(id) { function toggleLayerVisibility(id) {
@@ -3207,13 +3494,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div> <div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
</div> </div>
</div> </div>
<button class="iwb-editor-btn iwb-editor-btn-copy" data-action="copyClipboard" title="复制当前结果到系统剪贴板(可直接粘到聊天窗口/后台),不关闭编辑器">复制</button>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button> <button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button>
</div> </div>
</div> </div>
<div class="iwb-editor-optionbar"> <div class="iwb-editor-optionbar">
<span class="iwb-editor-optionbar-label">工具选项</span> <span class="iwb-editor-optionbar-label">工具选项</span>
<div class="iwb-editor-optionbar-body"></div> <div class="iwb-editor-optionbar-body"></div>
<span class="iwb-editor-optionbar-tip">选区也可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消</span> <span class="iwb-editor-optionbar-tip" title="选中后还可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消选区">Ctrl+J 复制 · Delete 清除</span>
</div> </div>
<div class="iwb-editor-main"> <div class="iwb-editor-main">
@@ -3242,7 +3530,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<canvas class="iwb-editor-selection-overlay"></canvas> <canvas class="iwb-editor-selection-overlay"></canvas>
<canvas class="iwb-editor-cursor-overlay"></canvas> <canvas class="iwb-editor-cursor-overlay"></canvas>
</div> </div>
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消"> <!-- v1.9:input → textarea,支持 Shift+Enter 换行(Enter 仍是确认) -->
<textarea class="iwb-editor-text-input" rows="1" wrap="off" placeholder="输入文字,Enter 确认,Shift+Enter 换行" spellcheck="false"></textarea>
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div> <div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 --> <!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 -->
<div class="iwb-editor-sel-bar"> <div class="iwb-editor-sel-bar">
@@ -3367,6 +3656,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效"> <input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
</div> </div>
<span class="iwb-color-pop-sep"></span> <span class="iwb-color-pop-sep"></span>
<!-- 最近使用(v1.9):由 recent-colors.js 动态填充,空的时候整行隐藏 -->
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
<div class="iwb-editor-color-swatches"> <div class="iwb-editor-color-swatches">
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button> <button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button> <button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button>
@@ -4027,6 +4318,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
crop: onCropDrawMove crop: onCropDrawMove
}; };
function onMouseMove(e) { function onMouseMove(e) {
S._altDown = !!e.altKey;
if (S.placingImage && S.placingHandle && S.placingStart) { if (S.placingImage && S.placingHandle && S.placingStart) {
onPlacementDragMove(e); onPlacementDragMove(e);
return; return;
@@ -4100,8 +4392,21 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (S.textDrag.mode === "move") { if (S.textDrag.mode === "move") {
const dx = pos0.x - S.textDrag.start.x; const dx = pos0.x - S.textDrag.start.x;
const dy = pos0.y - S.textDrag.start.y; const dy = pos0.y - S.textDrag.start.y;
t.x = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4)); let nx = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4));
t.y = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4)); let ny = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4));
if (!S._altDown) {
const b = textBounds(t);
const offX = b.x - t.x;
const offY = b.y - t.y;
const s = snapMove({ x: nx + offX, y: ny + offY, w: b.w, h: b.h }, otherObjectBoxes(t));
nx += s.dx;
ny += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
t.x = nx;
t.y = ny;
} else if (S.textDrag.mode === "rotate") { } else if (S.textDrag.mode === "rotate") {
const st = S.textDrag; const st = S.textDrag;
const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx); const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx);
@@ -4137,8 +4442,17 @@ var __IWB_ANNOTATE_MANIFEST__ = {
const dx = pos0.x - S.shapeDrag.start.x; const dx = pos0.x - S.shapeDrag.start.x;
const dy = pos0.y - S.shapeDrag.start.y; const dy = pos0.y - S.shapeDrag.start.y;
const b = shapeBounds(S.shapeDrag.shape); const b = shapeBounds(S.shapeDrag.shape);
const cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w))); let cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)));
const cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h))); let cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)));
if (!S._altDown) {
const box = { x: b.x + cdx, y: b.y + cdy, w: b.w, h: b.h };
const s = snapMove(box, otherObjectBoxes(sh));
cdx += s.dx;
cdy += s.dy;
S.guides = s.guides.length ? s.guides : null;
} else {
S.guides = null;
}
if (sh.type === "pen") { if (sh.type === "pen") {
sh.pts = (S.shapeDrag.shape.pts || []).map((p) => ({ x: p.x + cdx, y: p.y + cdy })); sh.pts = (S.shapeDrag.shape.pts || []).map((p) => ({ x: p.x + cdx, y: p.y + cdy }));
} else { } else {
@@ -4187,6 +4501,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
lw: Math.max(1, S.shapeLineWidth), lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth), lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false, fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0,
opacity: 1, opacity: 1,
visible: true visible: true
}; };
@@ -4295,6 +4610,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
} }
S.textDrag = null; S.textDrag = null;
S.guides = null;
renderObjects();
renderLayerPanel(); renderLayerPanel();
return; return;
} }
@@ -4310,6 +4627,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
} }
S.bitmapDrag = null; S.bitmapDrag = null;
S.guides = null;
renderObjects(); renderObjects();
renderLayerPanel(); renderLayerPanel();
return; return;
@@ -4324,6 +4642,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
} }
S.shapeDrag = null; S.shapeDrag = null;
S.guides = null;
renderObjects();
renderLayerPanel(); renderLayerPanel();
return; return;
} }
@@ -4370,6 +4690,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
color: S.color, color: S.color,
lw: Math.max(1, S.shapeLineWidth), lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false, fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false,
radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0,
opacity: 1, opacity: 1,
visible: true, visible: true,
locked: false, locked: false,
@@ -4588,6 +4909,46 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<button class="iwb-opt-btn${fill ? " active" : ""}" data-opt-toggle="fill" data-fill-owner="${owner}" data-value="fill" title="实心 (Shift+X 切换)">实心</button>`; <button class="iwb-opt-btn${fill ? " active" : ""}" data-opt-toggle="fill" data-fill-owner="${owner}" data-value="fill" title="实心 (Shift+X 切换)">实心</button>`;
} }
var SHAPE_NAMES = { rect: "矩形", circle: "圆形", arrow: "箭头", pen: "钢笔路径" }; var SHAPE_NAMES = { rect: "矩形", circle: "圆形", arrow: "箭头", pen: "钢笔路径" };
var TEXT_STYLE_STATE_KEY = {
fontWeight: "textWeight",
align: "textAlign",
lineHeight: "textLineHeight",
strokeWidth: "textStrokeWidth",
strokeColor: "textStrokeColor",
bgFill: "textBgFill",
bgColor: "textBgColor"
};
function textStyleValues(t) {
const pick = (objKey, stateKey, dflt) => {
const raw = t ? t[objKey] : S[stateKey];
return raw == null ? dflt : raw;
};
return {
fontWeight: String(pick("fontWeight", "textWeight", "bold")),
align: pick("align", "textAlign", "left"),
lineHeight: Number(pick("lineHeight", "textLineHeight", 1.25)) || 1.25,
strokeWidth: Math.max(0, Number(pick("strokeWidth", "textStrokeWidth", 0)) || 0),
strokeColor: pick("strokeColor", "textStrokeColor", "#ffffff"),
bgFill: !!pick("bgFill", "textBgFill", false),
bgColor: pick("bgColor", "textBgColor", "#000000")
};
}
function textStyleHTML(t) {
const v = textStyleValues(t);
const wBtn = (val, label, title) => `<button class="iwb-opt-btn${v.fontWeight === val ? " active" : ""}" data-opt-text="fontWeight" data-value="${val}" title="${title}">${label}</button>`;
const aBtn = (val, label, title) => `<button class="iwb-opt-btn${v.align === val ? " active" : ""}" data-opt-text="align" data-value="${val}" title="${title}">${label}</button>`;
return `<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">字重</span>${wBtn("normal", "常规", "常规字重")}${wBtn("bold", "粗", "粗体(默认)")}${wBtn("900", "特粗", "特粗,封面标题用")}
<span class="iwb-opt-label">对齐</span>${aBtn("left", "左", "多行时按左缘对齐")}${aBtn("center", "中", "多行时居中")}${aBtn("right", "右", "多行时按右缘对齐")}
<span class="iwb-opt-label">行距</span>
<input type="number" class="iwb-opt-num" data-opt="textLineHeight" min="80" max="300" step="5" value="${Math.round(v.lineHeight * 100)}"><span class="iwb-opt-unit">%</span>
<span class="iwb-opt-sep"></span>
<span class="iwb-opt-label">描边</span>
<input type="number" class="iwb-opt-num" data-opt="textStrokeWidth" min="0" max="40" step="1" value="${Math.round(v.strokeWidth)}"><span class="iwb-opt-unit">px</span>
<input type="color" class="iwb-opt-color" data-opt-color="strokeColor" value="${v.strokeColor}" title="描边颜色">
<button class="iwb-opt-btn${v.bgFill ? " active" : ""}" data-opt-text="bgFill" data-value="${v.bgFill ? "0" : "1"}" title="给文字加一块半透明底色,压在花背景上也能看清">底色</button>
<input type="color" class="iwb-opt-color" data-opt-color="bgColor" value="${v.bgColor}" title="底色颜色;选色会自动开启底色,不用先点左侧按钮">`;
}
var SELCMD_SVGS = { var SELCMD_SVGS = {
all: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 2"><rect x="3.5" y="3.5" width="17" height="17" rx="1"/></svg>', all: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 2"><rect x="3.5" y="3.5" width="17" height="17" rx="1"/></svg>',
invert: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><rect x="8" y="8" width="8" height="8" rx="1" fill="currentColor" stroke="none"/></svg>', invert: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><rect x="8" y="8" width="8" height="8" rx="1" fill="currentColor" stroke="none"/></svg>',
@@ -4604,15 +4965,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (t === "rect" || t === "circle" || t === "pen" || t === "arrow") { if (t === "rect" || t === "circle" || t === "pen" || t === "arrow") {
const owner = t === "pen" ? "pen" : "rect"; const owner = t === "pen" ? "pen" : "rect";
const lw = Math.max(1, Math.round(sh.lw || S.shapeLineWidth)); const lw = Math.max(1, Math.round(sh.lw || S.shapeLineWidth));
return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>` + rangeOpt("shapeLineWidth", "线宽", 1, 60, lw, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (t === "arrow" ? "" : fillStyleHTML(owner)) + (t === "pen" && !sh.closed ? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>' : "") + selCmdHTML(); return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>` + rangeOpt("shapeLineWidth", "线宽", 1, 60, lw, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (t === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, Math.round(sh.radius || 0), "px") : "") + (t === "arrow" ? "" : fillStyleHTML(owner)) + (t === "pen" && !sh.closed ? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>' : "") + selCmdHTML();
} }
} }
const text = getSelectedText(); const text = getSelectedText();
if (text) { if (text) {
return `<span class="iwb-opt-current">已选中:文字</span>` + rangeOpt("textSize", "字号", 8, 400, Math.round(text.fontSize || S.textSize), "px") + '<span class="iwb-opt-hint">双击文字改内容,拖动移动,手柄缩放</span>' + selCmdHTML(); return `<span class="iwb-opt-current">已选中:文字</span>` + rangeOpt("textSize", "字号", 8, 400, Math.round(text.fontSize || S.textSize), "px") + textStyleHTML(text) + selCmdHTML() + '<span class="iwb-opt-hint">双击改内容 · 拖动手柄缩放</span>';
} }
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span> return `<span class="iwb-opt-current">当前工具:选择 / 移动</span>` + selCmdHTML() + '<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里出现它的描边、实心与粗细</span>';
<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里会出现它的描边、实心与粗细</span>` + selCmdHTML();
} }
function optionBarHTML(tool) { function optionBarHTML(tool) {
if (tool === "crop") return cropOptionHTML(); if (tool === "crop") return cropOptionHTML();
@@ -4626,7 +4986,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>` + presetDots("brushHardness", [0, 25, 50, 75, 100]); <span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>` + presetDots("brushHardness", [0, 25, 50, 75, 100]);
} }
if (tool === "rect" || tool === "circle") { if (tool === "rect" || tool === "circle") {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + fillStyleHTML("rect"); return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (tool === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, S.shapeRadius, "px") : "") + fillStyleHTML("rect");
} }
if (tool === "arrow") { if (tool === "arrow") {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + '<span class="iwb-opt-hint">拖出箭头,松手完成</span>'; return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + '<span class="iwb-opt-hint">拖出箭头,松手完成</span>';
@@ -4635,7 +4995,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + fillStyleHTML("pen") + '<span class="iwb-opt-hint">逐点点击,点回起点闭合;闭合后可切换描边/实心</span>'; return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + fillStyleHTML("pen") + '<span class="iwb-opt-hint">逐点点击,点回起点闭合;闭合后可切换描边/实心</span>';
} }
if (tool === "text") { if (tool === "text") {
return rangeOpt("textSize", "字号", 8, 400, S.textSize, "px") + '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>'; return rangeOpt("textSize", "字号", 8, 400, S.textSize, "px") + textStyleHTML(null) + '<span class="iwb-opt-hint">点画布输入文字,Enter 确认,Shift+Enter 换行</span>';
} }
if (tool === "marquee") { if (tool === "marquee") {
return `<span class="iwb-opt-label">形状</span> return `<span class="iwb-opt-label">形状</span>
@@ -4675,7 +5035,10 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (key === "brushHardness") return S.brushHardness; if (key === "brushHardness") return S.brushHardness;
if (key === "brushOpacity") return Math.round(S.brushOpacity * 100); if (key === "brushOpacity") return Math.round(S.brushOpacity * 100);
if (key === "shapeLineWidth") return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth; if (key === "shapeLineWidth") return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth;
if (key === "shapeRadius") return selShape && selShape.type === "rect" ? Math.round(selShape.radius || 0) : S.shapeRadius;
if (key === "textSize") return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize; if (key === "textSize") return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize;
if (key === "textLineHeight") return Math.round((selText ? Number(selText.lineHeight) || S.textLineHeight : S.textLineHeight) * 100);
if (key === "textStrokeWidth") return Math.round(selText ? Number(selText.strokeWidth) || 0 : S.textStrokeWidth);
if (key === "feather") return S.selectionFeather; if (key === "feather") return S.selectionFeather;
return ""; return "";
}; };
@@ -4699,6 +5062,21 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
btn.classList.toggle("active", !!cur === (btn.dataset.value === "fill")); btn.classList.toggle("active", !!cur === (btn.dataset.value === "fill"));
}); });
const sv = textStyleValues(selText);
body.querySelectorAll("[data-opt-text]").forEach((btn) => {
const k = btn.dataset.optText;
if (k === "bgFill") {
btn.classList.toggle("active", !!sv.bgFill);
btn.dataset.value = sv.bgFill ? "0" : "1";
return;
}
btn.classList.toggle("active", String(sv[k]) === btn.dataset.value);
});
body.querySelectorAll("[data-opt-color]").forEach((inp) => {
if (document.activeElement === inp) return;
const v = sv[inp.dataset.optColor];
if (v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v;
});
} }
function updateStatusbar() { function updateStatusbar() {
if (!runtime.el) return; if (!runtime.el) return;
@@ -4746,6 +5124,50 @@ var __IWB_ANNOTATE_MANIFEST__ = {
renderObjects(); renderObjects();
if (committed) textSnapDone = false; if (committed) textSnapDone = false;
} }
var textStyleSnapDone = false;
function applyTextStyle(key, raw, committed) {
const stateKey = TEXT_STYLE_STATE_KEY[key];
if (!stateKey) return;
let value = raw;
if (key === "bgFill") value = raw === true || raw === 1 || raw === "1" || raw === "true";
else if (key === "lineHeight") value = clamp(Number(raw) || 125, 80, 300) / 100;
else if (key === "strokeWidth") value = clamp(Number(raw) || 0, 0, 40);
else if (key === "strokeColor" || key === "bgColor") value = String(raw || "#000000").toLowerCase();
else value = String(raw);
S[stateKey] = value;
const t = getSelectedText();
if (!t || t.locked) {
textStyleSnapDone = false;
return;
}
if (committed || !textStyleSnapDone) {
saveSnapshot("文字样式");
textStyleSnapDone = true;
}
t[key] = value;
if (key === "bgColor" && !t.bgFill) {
t.bgFill = true;
S.textBgFill = true;
}
renderObjects();
if (key === "bgColor") syncOptionBar();
if (committed) textStyleSnapDone = false;
}
var radiusSnapDone = false;
function applyShapeRadius(committed) {
const sh = getSelectedShape();
if (!sh || sh.locked || sh.type !== "rect") {
radiusSnapDone = false;
return;
}
if (committed || !radiusSnapDone) {
saveSnapshot("圆角");
radiusSnapDone = true;
}
sh.radius = S.shapeRadius;
renderObjects();
if (committed) radiusSnapDone = false;
}
function setShapeFill(fill, owner) { function setShapeFill(fill, owner) {
const isPen = owner === "pen"; const isPen = owner === "pen";
if (isPen) S.penFill = !!fill; if (isPen) S.penFill = !!fill;
@@ -4784,6 +5206,13 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} else if (key === "textSize") { } else if (key === "textSize") {
S.textSize = clamp(safe || 32, 8, 400); S.textSize = clamp(safe || 32, 8, 400);
applyTextSize(committed); applyTextSize(committed);
} else if (key === "textLineHeight") {
applyTextStyle("lineHeight", safe || 125, committed);
} else if (key === "textStrokeWidth") {
applyTextStyle("strokeWidth", safe, committed);
} else if (key === "shapeRadius") {
S.shapeRadius = clamp(safe, 0, 400);
applyShapeRadius(committed);
} else if (key === "feather") { } else if (key === "feather") {
S.selectionFeather = clamp(safe, 0, 20); S.selectionFeather = clamp(safe, 0, 20);
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather; if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather;
@@ -4856,8 +5285,25 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (body) { if (body) {
body.addEventListener("mousedown", (e) => e.stopPropagation()); body.addEventListener("mousedown", (e) => e.stopPropagation());
body.addEventListener("input", (e) => setOptionFromControl(e.target, false)); body.addEventListener("input", (e) => setOptionFromControl(e.target, false));
body.addEventListener("change", (e) => setOptionFromControl(e.target, true)); body.addEventListener("change", (e) => {
const colorEl = e.target.closest ? e.target.closest("[data-opt-color]") : null;
if (colorEl) {
e.stopPropagation();
applyTextStyle(colorEl.dataset.optColor, colorEl.value, true);
syncOptionBar();
return;
}
setOptionFromControl(e.target, true);
});
body.addEventListener("click", (e) => { body.addEventListener("click", (e) => {
const textBtn = e.target.closest("[data-opt-text]");
if (textBtn) {
e.stopPropagation();
const k = textBtn.dataset.optText;
applyTextStyle(k, textBtn.dataset.value, true);
syncOptionBar();
return;
}
const shapeBtn = e.target.closest('[data-opt="shape"]'); const shapeBtn = e.target.closest('[data-opt="shape"]');
if (shapeBtn) { if (shapeBtn) {
e.stopPropagation(); e.stopPropagation();
@@ -5041,10 +5487,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (panelHexInput) panelHexInput.addEventListener("change", () => { if (panelHexInput) panelHexInput.addEventListener("change", () => {
if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value); if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value);
}); });
runtime.el.querySelectorAll(".iwb-editor-color-panel-swatch").forEach((btn) => btn.addEventListener("click", (e) => { if (pop) {
pop.addEventListener("click", (e) => {
const btn = e.target.closest("[data-panel-color]");
if (!btn) return;
e.stopPropagation(); e.stopPropagation();
setPanelColor(btn.dataset.panelColor); setPanelColor(btn.dataset.panelColor);
})); });
}
const palettePick = runtime.el.querySelector('[data-action="palettePick"]'); const palettePick = runtime.el.querySelector('[data-action="palettePick"]');
if (palettePick) { if (palettePick) {
palettePick.addEventListener("mousedown", (e) => e.stopPropagation()); palettePick.addEventListener("mousedown", (e) => e.stopPropagation());
@@ -5243,6 +5693,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function bindExportActions() { function bindExportActions() {
bindIf('[data-action="cancel"]', "click", close); bindIf('[data-action="cancel"]', "click", close);
bindIf('[data-action="download"]', "click", () => exportResult("download")); bindIf('[data-action="download"]', "click", () => exportResult("download"));
bindIf('[data-action="copyClipboard"]', "click", () => copyResult());
bindIf('[data-action="newNode"]', "click", () => exportResult("newNode")); bindIf('[data-action="newNode"]', "click", () => exportResult("newNode"));
bindIf('[data-action="replace"]', "click", () => exportResult("replace")); bindIf('[data-action="replace"]', "click", () => exportResult("replace"));
} }
@@ -5251,10 +5702,16 @@ var __IWB_ANNOTATE_MANIFEST__ = {
} }
function bindTextInput() { function bindTextInput() {
const textInput = runtime.el.querySelector(".iwb-editor-text-input"); const textInput = runtime.el.querySelector(".iwb-editor-text-input");
textInput && textInput.addEventListener("mousedown", (e) => e.stopPropagation()); if (!textInput) return;
textInput && textInput.addEventListener("keydown", (e) => { textInput.addEventListener("mousedown", (e) => e.stopPropagation());
const autosize = () => {
textInput.style.height = "auto";
textInput.style.height = textInput.scrollHeight + 4 + "px";
};
textInput.addEventListener("input", autosize);
textInput.addEventListener("keydown", (e) => {
e.stopPropagation(); e.stopPropagation();
if (e.key === "Enter") { if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault(); e.preventDefault();
commitTextInput(); commitTextInput();
} else if (e.key === "Escape") { } else if (e.key === "Escape") {
@@ -6947,6 +7404,70 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}, 2e3); }, 2e3);
toast("已下载 " + name + "(" + Math.round(blob.size / 1024) + "KB)", "success"); toast("已下载 " + name + "(" + Math.round(blob.size / 1024) + "KB)", "success");
} }
async function toPngBlob(blob) {
try {
if (typeof createImageBitmap === "function") {
const bmp = await createImageBitmap(blob);
const c = document.createElement("canvas");
c.width = bmp.width;
c.height = bmp.height;
c.getContext("2d").drawImage(bmp, 0, 0);
if (typeof bmp.close === "function") bmp.close();
const out = await new Promise((res) => c.toBlob((b) => res(b), "image/png"));
c.width = 0;
c.height = 0;
if (out) return out;
}
} catch (e) {
}
return await new Promise((resolve) => {
const url = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
const c = document.createElement("canvas");
c.width = img.naturalWidth;
c.height = img.naturalHeight;
c.getContext("2d").drawImage(img, 0, 0);
try {
URL.revokeObjectURL(url);
} catch (e) {
}
c.toBlob((b) => resolve(b || blob), "image/png");
};
img.onerror = () => {
try {
URL.revokeObjectURL(url);
} catch (e) {
}
resolve(blob);
};
img.src = url;
});
}
async function copyBlobToClipboard(blob) {
const nav = typeof navigator !== "undefined" ? navigator : null;
const CI = typeof window !== "undefined" ? window.ClipboardItem : null;
if (!nav || !nav.clipboard || typeof nav.clipboard.write !== "function" || typeof CI !== "function") {
toast("当前浏览器不支持复制图片,请用「导出」下载", "warn");
return false;
}
let png = blob;
if (blob.type !== "image/png") {
try {
png = await toPngBlob(blob);
} catch (e) {
png = blob;
}
}
try {
await nav.clipboard.write([new CI({ "image/png": png })]);
toast("已复制到剪贴板(" + Math.round(png.size / 1024) + "KB),可直接粘贴", "success");
return true;
} catch (e) {
toast("复制失败:" + (e && e.message || "浏览器拒绝了剪贴板写入") + ";可用「导出」下载", "error");
return false;
}
}
// image-annotate/plugin/editor/index.js // image-annotate/plugin/editor/index.js
async function open(options) { async function open(options) {
@@ -6969,6 +7490,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
updateAllUI(); updateAllUI();
registerSelectionCommands(); registerSelectionCommands();
loadExportOptions(); loadExportOptions();
loadRecentColors();
bindLiteUI(); bindLiteUI();
bindFloating(); bindFloating();
bindExportUI(); bindExportUI();
@@ -7154,6 +7676,17 @@ var __IWB_ANNOTATE_MANIFEST__ = {
if (S.callbacks && S.callbacks.onError) S.callbacks.onError("导出失败:" + (e && e.message || "图片跨域")); if (S.callbacks && S.callbacks.onError) S.callbacks.onError("导出失败:" + (e && e.message || "图片跨域"));
} }
} }
async function copyResult() {
if (S.placingImage) cancelImagePlacement();
try {
const { blob } = await prepareOutput();
await copyBlobToClipboard(blob);
if (S.renderAll) S.renderAll();
} catch (e) {
console.error("[IWB编辑器] 复制失败:", e);
toast("复制失败:" + (e && e.message || "图片可能跨域"), "error");
}
}
var __stats = () => ({ var __stats = () => ({
history: S.history.length, history: S.history.length,
historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0), historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0),
@@ -7182,9 +7715,44 @@ var __IWB_ANNOTATE_MANIFEST__ = {
opacity: l.opacity == null ? 1 : l.opacity, opacity: l.opacity == null ? 1 : l.opacity,
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || "1") : null cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || "1") : null
})), })),
shapes: S.shapeLayers.map((s) => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color })), shapes: S.shapeLayers.map((s) => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
texts: S.textLayers.map((t) => ({ id: t.id, text: t.text })), texts: S.textLayers.map((t) => ({
id: t.id,
text: t.text,
x: t.x,
y: t.y,
fontSize: t.fontSize,
color: t.color,
fontWeight: t.fontWeight,
align: t.align,
lineHeight: t.lineHeight,
strokeWidth: t.strokeWidth,
strokeColor: t.strokeColor,
bgFill: !!t.bgFill,
bgColor: t.bgColor,
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
box: (() => {
const b = textBounds(t);
return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) };
})()
})),
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
guides: S.guides ? S.guides.map((g) => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
recentColors: (S.recentColors || []).slice(),
textDefaults: {
weight: S.textWeight,
align: S.textAlign,
lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth,
strokeColor: S.textStrokeColor,
bgFill: S.textBgFill,
bgColor: S.textBgColor
},
selectedShapeId: S.selectedShapeId, selectedShapeId: S.selectedShapeId,
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
drag: S.shapeDrag ? "shape:" + S.shapeDrag.mode + (S.shapeDrag.handle ? ":" + S.shapeDrag.handle : "") : S.textDrag ? "text:" + S.textDrag.mode : S.bitmapDrag ? "bitmap:" + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ":" + S.bitmapDrag.handle : "") : null,
selectedTextId: S.selectedTextId, selectedTextId: S.selectedTextId,
penEditId: S.penEditId, penEditId: S.penEditId,
activeLayerId: S.activeLayerId, activeLayerId: S.activeLayerId,
@@ -7279,7 +7847,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
}; };
// image-annotate/plugin/editor.css // image-annotate/plugin/editor.css
var editor_default = '/* IWB 鲜艺抠图节点 - 注入样式 */\n\n/* 抠图按钮 */\n.iwb-cutout-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n\n.iwb-cutout-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n}\n\n.iwb-cutout-btn svg {\n width: 14px;\n height: 14px;\n display: block;\n}\n\n/* 正在处理中的按钮状态 */\n.iwb-cutout-btn.processing {\n animation: iwb-cutout-pulse 1s infinite;\n pointer-events: none;\n}\n\n@keyframes iwb-cutout-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n}\n\n/* 全屏遮罩 */\n.iwb-cutout-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.25);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n z-index: 999999;\n pointer-events: all;\n backdrop-filter: blur(2px);\n}\n\n/* 自定义按钮提示(挂在 body,最高层级,不会被图片遮挡) */\n#iwb-cutout-tip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(30, 30, 46, 0.95);\n color: #fff;\n padding: 5px 10px;\n border-radius: 6px;\n font-size: 12px;\n line-height: 1.5;\n white-space: nowrap;\n pointer-events: none;\n display: none;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);\n border: 1px solid rgba(255, 255, 255, 0.14);\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n max-width: 320px;\n white-space: normal;\n word-break: break-all;\n}\n\n/* 加载动画 */\n.iwb-cutout-spinner {\n width: 48px;\n height: 48px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #e8a735;\n border-radius: 50%;\n animation: iwb-cutout-spin 0.8s linear infinite;\n}\n\n@keyframes iwb-cutout-spin {\n to { transform: rotate(360deg); }\n}\n\n/* 遮罩文字 */\n.iwb-cutout-text {\n color: #fff;\n font-size: 14px;\n font-weight: 500;\n text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);\n background: rgba(0, 0, 0, 0.6);\n padding: 8px 16px;\n border-radius: 6px;\n}\n\n/* Toast 提示 */\n.iwb-cutout-toast {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n z-index: 999999;\n transition: opacity 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: none;\n max-width: 400px;\n}\n\n.iwb-cutout-toast-success {\n background: #1a7f37;\n color: #fff;\n}\n\n.iwb-cutout-toast-error {\n background: #cf222e;\n color: #fff;\n}\n\n.iwb-cutout-toast-info {\n background: #1f6feb;\n color: #fff;\n}\n\n/* 白底按钮 */\n.iwb-whitebg-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-whitebg-btn:hover { opacity: 1; transform: scale(1.15); }\n.iwb-whitebg-btn svg { width: 14px; height: 14px; display: block; }\n.iwb-whitebg-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n/* 编辑按钮 */\n.iwb-editor-btn-icon {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-editor-btn-icon:hover { opacity: 1; transform: scale(1.15); }\n.iwb-editor-btn-icon svg { width: 14px; height: 14px; display: block; }\n\n/* ==================== 图片编辑器 ==================== */\n\n.iwb-editor-overlay {\n position: fixed;\n top: 0; left: 0;\n width: 100%; height: 100%;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999998;\n backdrop-filter: blur(3px);\n}\n\n.iwb-editor-modal {\n background: #1e1e2e;\n border-radius: 0;\n box-shadow: none;\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n overflow: visible;\n}\n\n/* 新增:主区域(画布 + 图层面板)flex 布局 */\n.iwb-editor-main {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n overflow: visible;\n}\n\n.iwb-editor-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 16px;\n background: #181825;\n border-bottom: 1px solid #313244;\n flex-wrap: nowrap;\n}\n.iwb-editor-header > .iwb-editor-tools {\n position: absolute;\n left: 12px;\n top: 68px;\n width: 44px;\n flex-direction: column;\n padding: 6px;\n background: #181825;\n border: 1px solid #313244;\n border-radius: 8px;\n z-index: 20;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { position: static; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] {\n position: absolute;\n top: -54px;\n left: auto;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"] { right: 154px; }\n.iwb-editor-header > .iwb-edLine truncated var editor_default = '/* IWB 鲜艺抠图节点 - 注入样式 */\n\n/* 抠图按钮 */\n.iwb-cutout-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n\n.iwb-cutout-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n}\n\n.iwb-cutout-btn svg {\n width: 14px;\n height: 14px;\n display: block;\n}\n\n/* 正在处理中的按钮状态 */\n.iwb-cutout-btn.processing {\n animation: iwb-cutout-pulse 1s infinite;\n pointer-events: none;\n}\n\n@keyframes iwb-cutout-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n}\n\n/* 全屏遮罩 */\n.iwb-cutout-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.25);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n z-index: 999999;\n pointer-events: all;\n backdrop-filter: blur(2px);\n}\n\n/* 自定义按钮提示(挂在 body,最高层级,不会被图片遮挡) */\n#iwb-cutout-tip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(30, 30, 46, 0.95);\n color: #fff;\n padding: 5px 10px;\n border-radius: 6px;\n font-size: 12px;\n line-height: 1.5;\n white-space: nowrap;\n pointer-events: none;\n display: none;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);\n border: 1px solid rgba(255, 255, 255, 0.14);\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n max-width: 320px;\n white-space: normal;\n word-break: break-all;\n}\n\n/* 加载动画 */\n.iwb-cutout-spinner {\n width: 48px;\n height: 48px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #e8a735;\n border-radius: 50%;\n animation: iwb-cutout-spin 0.8s linear infinite;\n}\n\n@keyframes iwb-cutout-spin {\n to { transform: rotate(360deg); }\n}\n\n/* 遮罩文字 */\n.iwb-cutout-text {\n color: #fff;\n font-size: 14px;\n font-weight: 500;\n text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);\n background: rgba(0, 0, 0, 0.6);\n padding: 8px 16px;\n border-radius: 6px;\n}\n\n/* Toast 提示 */\n.iwb-cutout-toast {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n z-index: 999999;\n transition: opacity 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: none;\n max-width: 400px;\n}\n\n.iwb-cutout-toast-success {\n background: #1a7f37;\n color: #fff;\n}\n\n.iwb-cutout-toast-error {\n background: #cf222e;\n color: #fff;\n}\n\n.iwb-cutout-toast-info {\n background: #1f6feb;\n color: #fff;\n}\n\n/* 白底按钮 */\n.iwb-whitebg-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-whitebg-btn:hover { opacity: 1; transform: scale(1.15); }\n.iwb-whitebg-btn svg { width: 14px; height: 14px; display: block; }\n.iwb-whitebg-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n/* 编辑按钮 */\n.iwb-editor-btn-icon {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-editor-btn-icon:hover { opacity: 1; transform: scale(1.15); }\n.iwb-editor-btn-icon svg { width: 14px; height: 14px; display: block; }\n\n/* ==================== 图片编辑器 ==================== */\n\n.iwb-editor-overlay {\n position: fixed;\n top: 0; left: 0;\n width: 100%; height: 100%;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999998;\n backdrop-filter: blur(3px);\n}\n\n.iwb-editor-modal {\n background: #1e1e2e;\n border-radius: 0;\n box-shadow: none;\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n overflow: visible;\n}\n\n/* 新增:主区域(画布 + 图层面板)flex 布局 */\n.iwb-editor-main {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n overflow: visible;\n}\n\n.iwb-editor-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 16px;\n background: #181825;\n border-bottom: 1px solid #313244;\n flex-wrap: nowrap;\n}\n.iwb-editor-header > .iwb-editor-tools {\n position: absolute;\n left: 12px;\n top: 68px;\n width: 44px;\n flex-direction: column;\n padding: 6px;\n background: #181825;\n border: 1px solid #313244;\n border-radius: 8px;\n z-index: 20;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { position: static; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] {\n position: absolute;\n top: -54px;\n left: auto;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"] { right: 154px; }\n.iwb-editor-header > .iwb-edLine truncated
// image-annotate/plugin/glue.js // image-annotate/plugin/glue.js
function createGlue(ctx, css) { function createGlue(ctx, css) {
+291
View File
@@ -1659,6 +1659,297 @@ check('图层拖动排序:位图与矢量混排也能拖(面板顺序、z、
return geo.vecIdx >= 1 ? true : '矢量画布在 DOM 里排到了最底 vecIdx=' + geo.vecIdx return geo.vecIdx >= 1 ? true : '矢量画布在 DOM 里排到了最底 vecIdx=' + geo.vecIdx
})()) })())
// ---------- v1.9 文字样式 / 吸附参考线 / 圆角 / 最近色 / 复制 ----------
/** 图片坐标 → 屏幕坐标(用位图图层 canvas 的实际显示尺寸换算,别用 zoom 猜) */
async function imgToScreen(ix, iy) {
const b = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
const d = await dbg()
return { x: b.x + ix * (b.width / d.doc.w), y: b.y + iy * (b.height / d.doc.h), box: b, doc: d.doc }
}
/** 吸附阈值(图片像素):与 snap.js 的 6 屏幕像素保持同一口径 */
async function snapTol() {
const d = await dbg()
const b = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
return 6 / (b.width / d.doc.w)
}
// 文字输入框必须贴着点击点出现。早先用 canvasStack 的矩形换算,而 stack 尺寸是
// (imgW + 2*overlayPad)*scale、图片在 stack 内还额外偏移 pad*scale —— 比例偏小又漏偏移,
// 输入框整体跑到点击点的左上方。
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
const clearPt = await imgToScreen(90, 8)
await page.mouse.click(clearPt.x, clearPt.y)
await page.waitForTimeout(180)
await page.locator('.iwb-editor-tool[data-tool="text"]').click()
await page.waitForTimeout(180)
// 测试画布只有 96×64,取左下角的空白区(已存在的两个矩形都在上半部)
const clickPt = await imgToScreen(12, 56)
await page.mouse.click(clickPt.x, clickPt.y)
await page.waitForTimeout(260)
const inpBox = await page.locator('.iwb-editor-text-input').boundingBox()
if (!inpBox) throw new Error('点了画布但文字输入框没有出现,后面的定位断言无从谈起')
// 输入框内「文字起点」= 左边框 2px + 左内边距 8px、上边框 2px + 上内边距 4px
const dxInp = inpBox.x + 10 - clickPt.x
const dyInp = inpBox.y + 6 - clickPt.y
check('文字输入框贴着点击点出现(不再偏到左上方)',
Math.abs(dxInp) <= 3 && Math.abs(dyInp) <= 3,
'dx=' + dxInp.toFixed(1) + ' dy=' + dyInp.toFixed(1))
await page.keyboard.press('Escape')
await page.waitForTimeout(180)
check('输入框按 Esc 取消后不留下空文字对象', (await dbg()).texts.length === 0,
'texts=' + (await dbg()).texts.length)
// 多行文字:Shift+Enter 换行(textarea)→ 落成两行,包围盒高度约为单行两倍
await page.locator('.iwb-editor-tool[data-tool="text"]').click()
let p0 = await imgToScreen(8, 8)
await page.mouse.click(p0.x, p0.y)
await page.waitForTimeout(150)
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-text-input')
el.focus()
el.value = 'AB\nCD'
el.dispatchEvent(new Event('input', { bubbles: true }))
})
await page.keyboard.press('Enter')
await page.waitForTimeout(220)
let vdbg = await dbg()
const multiLine = vdbg.texts.length === 1 && vdbg.texts[0].text.indexOf('\n') > 0
const singleH = vdbg.texts.length ? vdbg.texts[0].fontSize * 1.25 : 0
check('文字支持多行(Shift+Enter 换行,包围盒高 ≈ 两行)',
multiLine && vdbg.texts[0].box.h >= singleH * 2 - 2,
multiLine ? 'h=' + vdbg.texts[0].box.h + ' 单行=' + Math.round(singleH) : JSON.stringify(vdbg.texts))
// 选择工具在「未选中任何元素」时也必须露出全选/反选/取消三个图标,且只能有一组。
// 它们曾被排在 margin-left:auto 的 hint 之后,被一路推到最右、滚出可视区,
// 表现就是「文字工具下有这三个按钮,切到选择工具就没了」。
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
const blankPt = await imgToScreen(60, 90)
await page.mouse.click(blankPt.x, blankPt.y)
await page.waitForTimeout(220)
const selIconNoSel = await page.locator('.iwb-editor-optionbar-body .iwb-opt-selcmd').count()
check('选择工具未选中元素时仍有全选/反选/取消三个图标(且不重复)',
selIconNoSel === 3, 'count=' + selIconNoSel)
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
p0 = await imgToScreen(10, 12)
await page.mouse.click(p0.x, p0.y)
await page.waitForTimeout(200)
vdbg = await dbg()
check('选中文字后选项栏出整套文字样式控件(字重/对齐/行距/描边/底色)',
Boolean(vdbg.selectedTextId) &&
(await page.locator('.iwb-editor-optionbar-body [data-opt-text="fontWeight"]').count()) === 3 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt-text="align"]').count()) === 3 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt-text="bgFill"]').count()) === 1 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt="textLineHeight"]').count()) >= 1 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt-color]').count()) === 2)
await page.locator('.iwb-editor-optionbar-body [data-opt-text="fontWeight"][data-value="900"]').click()
await page.waitForTimeout(150)
vdbg = await dbg()
const boldBefore = vdbg.texts[0].fontWeight
check('点「特粗」改选中文字的字重', boldBefore === '900', 'fontWeight=' + boldBefore)
await page.keyboard.press('Control+z')
await page.waitForTimeout(200)
vdbg = await dbg()
check('字重改动可撤销', vdbg.texts[0].fontWeight !== '900', 'fontWeight=' + vdbg.texts[0].fontWeight)
// 撤销会清掉选中态(历史恢复后不再高亮),要继续改样式得重新选中
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
p0 = await imgToScreen(10, 12)
await page.mouse.click(p0.x, p0.y)
await page.waitForTimeout(200)
vdbg = await dbg()
const hBefore = vdbg.texts[0].box.h
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-optionbar-body input[data-opt="textStrokeWidth"]')
el.value = '6'
el.dispatchEvent(new Event('input', { bubbles: true }))
el.dispatchEvent(new Event('change', { bubbles: true }))
})
await page.waitForTimeout(200)
vdbg = await dbg()
check('描边走选项栏生效且包围盒随之变大(含描边外扩)',
vdbg.texts[0].strokeWidth === 6 && vdbg.texts[0].box.h > hBefore,
'sw=' + vdbg.texts[0].strokeWidth + ' h ' + hBefore + '→' + vdbg.texts[0].box.h)
// 底色块
await page.locator('.iwb-editor-optionbar-body [data-opt-text="bgFill"]').click()
await page.waitForTimeout(200)
vdbg = await dbg()
const hBg = vdbg.texts[0].box.h
check('底色块开关生效(padding 让包围盒继续变大)',
vdbg.texts[0].bgFill === true && hBg > vdbg.texts[0].box.h - 1 && hBg > 0,
'bgFill=' + vdbg.texts[0].bgFill + ' h=' + hBg)
// 只改底色颜色、不点「底色」开关时,画布上原本什么都不会变 —— 用户会以为底色坏了
// 或被别的颜色盖住。现在选色即自动启用,按钮的 active 态也要跟着亮。
await page.locator('.iwb-editor-optionbar-body [data-opt-text="bgFill"]').click()
await page.waitForTimeout(180)
const bgOff = (await dbg()).texts[0].bgFill
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-optionbar-body [data-opt-color="bgColor"]')
el.value = '#ffd400'
el.dispatchEvent(new Event('change', { bubbles: true }))
})
await page.waitForTimeout(220)
vdbg = await dbg()
const bgBtnOn = await page.evaluate(() =>
document.querySelector('.iwb-editor-optionbar-body [data-opt-text="bgFill"]').classList.contains('active'))
check('只选底色颜色就自动开启底色(不必先点开关)',
bgOff === false && vdbg.texts[0].bgFill === true && vdbg.texts[0].bgColor === '#ffd400' && bgBtnOn,
'关前=' + bgOff + ' 改色后 bgFill=' + vdbg.texts[0].bgFill +
' bgColor=' + vdbg.texts[0].bgColor + ' 按钮 active=' + bgBtnOn)
// 吸附:画一个实心矩形,拖到画布中心附近应被精确吸到中心并出现参考线
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await page.waitForTimeout(100)
if (await page.locator('.iwb-editor-optionbar-body [data-opt-toggle="fill"][data-fill-owner="rect"]').getAttribute('class').then(c => c.indexOf('active') < 0)) {
await page.locator('.iwb-editor-optionbar-body [data-opt-toggle="fill"][data-fill-owner="rect"]').click()
}
let pa = await imgToScreen(6, 6)
let pb = await imgToScreen(26, 26)
await page.mouse.move(pa.x, pa.y)
await page.mouse.down()
await page.mouse.move(pb.x, pb.y, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(200)
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
pa = await imgToScreen(16, 16)
await page.mouse.click(pa.x, pa.y)
// 等过 380ms 的双击窗口:同一个点连点会被判成双击(双击属于「进对象编辑」,
// 不该接管拖动),这里要测的是单击选中后的拖动
await page.waitForTimeout(420)
const rectGeo = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const s = d.shapes[d.shapes.length - 1]
return s ? { id: s.id } : null
})
const tol = await snapTol()
const sBox = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const cv = [...document.querySelectorAll('.iwb-editor-canvas-stack > canvas.iwb-editor-vec-canvas')]
return { doc: d.doc, shapes: d.shapes.length }
})
// 抓矩形中心,拖到「画布中心 + tol/2」:若吸附生效,中心会精确回到画布中心
const rectInfo = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const sel = d.selectedShapeId
return sel ? { sel, doc: d.doc } : { doc: d.doc }
})
const center = { x: sBox.doc.w / 2, y: sBox.doc.h / 2 }
// 用轴对齐假设取矩形中心:从墨迹范围读更稳(矩形是自己画的 6..26)
const inkBox = await page.evaluate(() => {
const cv = [...document.querySelectorAll('.iwb-editor-canvas-stack > canvas.iwb-editor-vec-canvas')]
let best = null
for (const c of cv) {
const cx = c.getContext('2d')
const d = cx.getImageData(0, 0, c.width, c.height).data
let minX = 1e9, minY = 1e9, maxX = -1, maxY = -1
for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) {
if (d[(y * c.width + x) * 4 + 3] > 20) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y }
}
if (maxX >= 0) best = { minX, minY, maxX, maxY, w: maxX - minX + 1, h: maxY - minY + 1 }
}
return best
})
const rc = { x: (inkBox.minX + inkBox.maxX + 1) / 2, y: (inkBox.minY + inkBox.maxY + 1) / 2 }
const grab = await imgToScreen(rc.x, rc.y)
const destImg = { x: center.x + tol / 2, y: center.y + tol / 2 }
const dest = await imgToScreen(destImg.x, destImg.y)
await page.mouse.move(grab.x, grab.y)
await page.mouse.down()
await page.mouse.move(grab.x + 3, grab.y + 3, { steps: 3 })
await page.mouse.move(dest.x, dest.y, { steps: 8 })
await page.waitForTimeout(160)
const gMid = (await dbg()).guides
await page.mouse.up()
await page.waitForTimeout(220)
const gEnd = (await dbg()).guides
// 松手后按墨迹中心核对:应该正好落在画布中心
const inkAfter = await page.evaluate(() => {
const cv = [...document.querySelectorAll('.iwb-editor-canvas-stack > canvas.iwb-editor-vec-canvas')]
let best = null
for (const c of cv) {
const cx = c.getContext('2d')
const d = cx.getImageData(0, 0, c.width, c.height).data
let minX = 1e9, minY = 1e9, maxX = -1, maxY = -1
for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) {
if (d[(y * c.width + x) * 4 + 3] > 20) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y }
}
if (maxX >= 0) best = { minX, minY, maxX, maxY }
}
return best
})
const cAfter = { x: (inkAfter.minX + inkAfter.maxX + 1) / 2, y: (inkAfter.minY + inkAfter.maxY + 1) / 2 }
check('拖到画布中心附近会被精确吸附(中心误差 < 1px)',
gMid.length >= 1 && Math.abs(cAfter.x - center.x) < 1 && Math.abs(cAfter.y - center.y) < 1,
'guides=' + JSON.stringify(gMid) + ' 中心=' + Math.round(cAfter.x) + ',' + Math.round(cAfter.y) + ' 期望=' + center.x + ',' + center.y)
check('松手后参考线清除', gEnd.length === 0, JSON.stringify(gEnd))
// Alt 拖动不吸附
const grab2 = await imgToScreen(cAfter.x, cAfter.y)
await page.keyboard.down('Alt')
await page.mouse.move(grab2.x, grab2.y)
await page.mouse.down()
await page.mouse.move(grab2.x + 4, grab2.y + 4, { steps: 4 })
await page.waitForTimeout(140)
const gAlt = (await dbg()).guides
await page.mouse.up()
await page.keyboard.up('Alt')
check('按住 Alt 拖动时不吸附(无参考线)', gAlt.length === 0, JSON.stringify(gAlt))
// 圆角:设半径后角落被切掉,墨迹变少
// 所有矢量层墨迹的总和:前面用例画过别的矩形,只取「最大那层」会量错对象
const inkCount = () => page.evaluate(() => {
const cv = [...document.querySelectorAll('.iwb-editor-canvas-stack > canvas.iwb-editor-vec-canvas')]
let total = 0
for (const c of cv) {
const d = c.getContext('2d').getImageData(0, 0, c.width, c.height).data
for (let i = 3; i < d.length; i += 4) if (d[i] > 20) total++
}
return total
})
const inkSharp = await inkCount()
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-optionbar-body input[data-opt="shapeRadius"]')
el.value = '6'
el.dispatchEvent(new Event('input', { bubbles: true }))
el.dispatchEvent(new Event('change', { bubbles: true }))
})
await page.waitForTimeout(220)
const inkRound = await inkCount()
const radiusVal = (await dbg()).shapes.map(s => s.radius).filter(r => r > 0)
check('矩形圆角生效(角落被切,墨迹减少)',
radiusVal.length === 1 && inkRound < inkSharp,
'radius=' + JSON.stringify(radiusVal) + ' ink ' + inkSharp + '→' + inkRound)
// 最近使用颜色
await page.locator('[data-action="toggleColorPop"]').click()
await page.waitForTimeout(150)
await page.locator('.iwb-editor-color-pop [data-panel-color="#ffd400"]').first().click()
await page.waitForTimeout(200)
const recents = (await dbg()).recentColors
const recentsInPop = await page.locator('.iwb-editor-recent-colors [data-panel-color]').count()
await page.keyboard.press('Escape')
await page.waitForTimeout(120)
check('选过的颜色进入「最近使用」并出现在色板弹层',
recents[0] === '#ffd400' && recentsInPop >= 1,
JSON.stringify(recents) + ' 弹层色块=' + recentsInPop)
// 复制到剪贴板:harness 跑在 about:blank(非安全上下文),
// 这里只验「按钮存在 + 点击有明确反馈 + 不抛错」,真安全上下文由本地 http 探针覆盖
const copyExists = await page.locator('[data-action="copyClipboard"]').count()
await page.locator('[data-action="copyClipboard"]').click()
await page.waitForTimeout(400)
const copyToast = await page.locator('.iwb-editor-toast').textContent()
check('顶栏有「复制」且点击给出明确反馈(非静默失败)',
copyExists === 1 && /复制/.test(copyToast || ''),
'toast=' + JSON.stringify(copyToast))
check('无选中时 Ctrl+] 有 toast 提示(不再无声失败)', await (async () => { check('无选中时 Ctrl+] 有 toast 提示(不再无声失败)', await (async () => {
await page.keyboard.press('Escape') // 清掉可能残留的选中态 await page.keyboard.press('Escape') // 清掉可能残留的选中态
await page.keyboard.press('Control+]') await page.keyboard.press('Control+]')