feat(image-annotate): 1.2.0 非破坏性裁剪(可撤销/不 flatten)+ 工具参数解耦与就地选项栏

This commit is contained in:
qiqi committed 2026-11-04 18:30:54 +08:00
1 parent a4e89f5f8b
commit d8e4e0cb26
13 files changed
+1768 -1243

No files matched your search

+17 -1
View File
@@ -41,7 +41,23 @@
两者只在电商预设下可见;`≤KB` 也只在该预设下参与降质 —— 切回「原尺寸」会把 `maxKB` 写回 0,
不会因为宿主里残留的 `exportMaxKB` 让限制「复活」或让原尺寸偷偷降质。
- **v1.1.2**:下载后与「还原原图(尺寸复位)」后都会走统一重绘,摘要里的尺寸和「上次输出 …KB」即时更新。
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,54 项);
### v1.2:非破坏性裁剪 + 工具参数解耦
- **裁剪可撤销**:`confirmCrop()` 不再合成成一张图、也不再把 `S.history` 清零,改为
① 先 `saveSnapshot('裁剪')`;② **逐图层**把可见区域搬进新尺寸画布(图层名/透明度/锁定全保留);
③ `viewport.js#resizeWorkspace()` 只换尺寸不重建图层。撤销时 `restoreState()` 会先把画布尺寸
复位到快照里的 `imgW/imgH` 再回填像素,所以 Ctrl+Z / Ctrl+Shift+Z 能来回切。
- **工具参数解耦**:新增 `S.shapeLineWidth`(矩形/圆形/箭头/钢笔线宽)与 `S.textSize`(文字字号),
不再借用 `S.brushSize` —— 以前「调细画笔」会顺手改掉所有形状描边、文字大小也跟画笔联动。
- **就地选项栏**:每个工具在顶栏下方都有自己最常用的 2–4 个参数
(画笔/橡皮:大小·硬度·透明;矩形/圆形:线宽·描边/实心;箭头/钢笔:线宽;文字:字号;
框选:形状·羽化;套索:羽化)。控件直接写回 `S`,与右侧参数面板双向同步;
选中形状/文字时调线宽或字号会同步改选中对象,松手才记一步历史。
- **打断输入的修复**:`renderAll()` 不再整块重建选项栏(改为 `syncOptionBar()` 只更新值),
拖滑杆和输数字不会被重绘打断;`isTyping()` 只对文字输入框为真,参数数字框里按
`Ctrl+A / Ctrl+J / Delete / Esc` 不再被当成「正在打字」吞掉。
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,65 项);
`node image-annotate/tools/e2e-site.mjs`(真站 CSP/SRI,发布后)。
## 入口
+2 -1
View File
@@ -305,7 +305,8 @@ getCompositeCanvas() // 当前这一张
| P0 交互 overlay 分层 | ✅ 新增 `selectionCanvas` / `cursorCanvas`,原 `overlayCanvas` 保留为交互层;三者尺寸与坐标基准由 `viewport.js` 统一同步 |
| P0 轻量 UI | ✅ 精简顶栏、就地选项栏、状态栏、侧栏一键收起、更多 ▾、粘贴一步落层;CSS 以末尾追加方式覆盖历史魔数定位(未整体重写) |
| P1 选区 | ✅ 矩形/椭圆/套索、羽化、反选/全选/取消、蚂蚁线、复制/剪切到新层、Delete(单层)、填充、画笔/橡皮受选区约束;加减选与选区变换留二期 |
| P2 非破坏性裁剪 | ⏳ 未做(仍会 flatten 且清历史);「还原原图」在尺寸变化路径会明确提示不可撤销 |
| P2 非破坏性裁剪 | ✅ v1.2.0:不再 flatten、不再清历史;逐图层搬运 + `resizeWorkspace()` 换尺寸,`restoreState()` 先复位尺寸再回填像素,可 Ctrl+Z / Ctrl+Shift+Z |
| 工具参数解耦与选项栏 | ✅ v1.2.0:`S.shapeLineWidth` / `S.textSize` 独立于 `S.brushSize`;选项栏按工具出参数(画笔三参、形状线宽+填充、文字字号、选区形状/羽化),与右侧面板双向同步 |
| P3 图层增强 | ⏳ 未做(缩略图 / 混合模式 / 蒙版) |
| P4 单张输出 | ✅ PNG/JPG/WebP、透明/白底、800×800(长边 80%)、≤500KB 迭代降质、下载、设置记忆;无队列 |
| 历史快照升级 | ✅ `snapshotState()` 记录完整图层集合(含 image 引用),能撤销「新建/删除图层」,这是复制新层与还原原图可撤销的前提 |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.1.2",
"version": "1.2.0",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
+17
View File
@@ -1485,3 +1485,20 @@
opacity: 0.32; cursor: not-allowed; text-decoration: line-through;
}
.iwb-editor-export-settings [data-export-key]:disabled:hover { background: #313244; }
/* 选项栏参数控件(v1.2):滑杆 + 数字框 + 实时读数,一行放得下就该保持一行 */
.iwb-opt-range {
width: 84px; height: 4px; flex: 0 0 auto;
accent-color: #4488ff; cursor: pointer;
}
.iwb-opt-val {
min-width: 32px; flex: 0 0 auto; color: #e8a735; font-size: 11px;
font-variant-numeric: tabular-nums; text-align: right;
}
.iwb-opt-unit { color: #7f849c; font-size: 11px; flex: 0 0 auto; }
/* 窄屏:参数多到放不下时横向滚动,不换行(换行会把 36px 高的选项栏撑开压画布) */
.iwb-editor-optionbar-body { overflow-x: auto; scrollbar-width: none; }
.iwb-editor-optionbar-body::-webkit-scrollbar { display: none; }
@media (max-width: 1100px) {
.iwb-opt-range { width: 64px; }
}
+83 -63
View File
@@ -1,14 +1,15 @@
/* crop.js - 裁剪工具
* 节:裁剪、裁剪栏。
* 遮罩绘制写 S.overlayCanvas,确认裁剪后重绘位图图层。
* 遮罩绘制写 S.overlayCanvas;确认裁剪后逐图层搬运像素(v1.2 起不再 flatten)。
*/
'use strict'
import { S, runtime } from './state.js'
import { getCompositeCanvas } from './tools.js'
import { setupCanvas } from './viewport.js'
import { resizeWorkspace } from './viewport.js'
import { disposeSelection } from './selection.js'
import { saveSnapshot } from './history.js'
import { toast } from './commands.js'
// ============ 裁剪 ============
@@ -235,59 +236,80 @@ import { disposeSelection } from './selection.js'
S.cropRect = { x: nx, y: ny, w: nw, h: nh }
}
/**
* 确认裁剪(v1.2 起非破坏性:可撤销、不 flatten)。
*
* 旧实现把可见图层合成成一张图再 setupCanvas,等于:① 所有图层被合并成一张;
* ② S.history 直接清零 —— 裁错了没有任何退路。现在改为:
* ① 先 saveSnapshot('裁剪'),快照记的是「裁剪前」的尺寸 + 每层像素;
* ② 逐图层把可见区域搬进新尺寸的 canvas(图层结构、命名、透明度、锁定全保留);
* ③ resizeWorkspace 只换尺寸不重建图层,像素随后写回。
* 撤销时 restoreState 会先把画布尺寸复位到快照里的 imgW/imgH,再回填像素。
*/
export function confirmCrop() {
if (!S.cropRect) return
const { x, y, w, h } = S.cropRect
if (w < 2 || h < 2) { cancelCrop(); return }
// 画布尺寸即将变化:旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效,
// 必须按 disposeSelection 级别清理,否则之后 Delete 会按旧 bbox
// 在新画布上开超大掩膜,把当前层整层擦掉。
disposeSelection()
// 合成所有可见图层
const tmp = getCompositeCanvas()
const sx = Math.round(x), sy = Math.round(y)
const sw = Math.round(w), sh = Math.round(h)
const cropC = document.createElement('canvas')
const c = S.cropConstraint
// 计算实际在原图范围内的源区域(裁剪框可超出原图边界,超出部分为透明)
const srcX = Math.max(0, sx)
const srcY = Math.max(0, sy)
const srcRight = Math.min(S.imgW, sx + sw)
const srcBottom = Math.min(S.imgH, sy + sh)
const srcW = Math.max(0, srcRight - srcX)
const srcH = Math.max(0, srcBottom - srcY)
// 在裁剪画布中的偏移
const dstX = srcX - sx
const dstY = srcY - sy
if (c.type === 'size' && c.sizeW > 0 && c.sizeH > 0) {
// 尺寸约束:先画到 sw×sh 画布再缩放到目标尺寸
cropC.width = c.sizeW
cropC.height = c.sizeH
const cctx = cropC.getContext('2d')
const scaleX = c.sizeW / sw
const scaleY = c.sizeH / sh
if (srcW > 0 && srcH > 0) {
cctx.drawImage(tmp, srcX, srcY, srcW, srcH,
dstX * scaleX, dstY * scaleY, srcW * scaleX, srcH * scaleY)
}
S.imgW = c.sizeW
S.imgH = c.sizeH
} else {
cropC.width = sw
cropC.height = sh
const cctx = cropC.getContext('2d')
if (srcW > 0 && srcH > 0) {
cctx.drawImage(tmp, srcX, srcY, srcW, srcH, dstX, dstY, srcW, srcH)
}
S.imgW = sw
S.imgH = sh
}
// 文字/形状图层坐标随裁剪区域变换
const sx = Math.round(x), sy = Math.round(y)
const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h))
const isSize = c.type === 'size' && c.sizeW > 0 && c.sizeH > 0
const scaleX = isSize ? c.sizeW / sw : 1
const scaleY = isSize ? c.sizeH / sh : 1
const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw
const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh
// 完全没变就别记一步空历史
if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) { cancelCrop(); return }
const oldW = S.imgW, oldH = S.imgH
const scaleX = nw / sw, scaleY = nh / sh
// 裁剪框可以超出画面:源矩形先夹到画面内,目标矩形按同一比例落位(超出部分为透明)
const srcX = Math.max(0, sx), srcY = Math.max(0, sy)
const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX)
const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY)
const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY
const dstW = srcW * scaleX, dstH = srcH * scaleY
// ① 进历史:快照记「裁剪前」的尺寸与每层像素
saveSnapshot('裁剪')
// ② 旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效
disposeSelection()
// ③ 逐图层把可见区域搬出来(保留图层结构,不再合成成一张)
const staged = S.layers.map(layer => {
const tmp = document.createElement('canvas')
tmp.width = nw
tmp.height = nh
if (srcW > 0 && srcH > 0) {
try {
tmp.getContext('2d').drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH)
} catch (e) { /* 单层搬运失败不阻断其余 */ }
}
return tmp
})
// ④ 换尺寸(会清空图层像素)后把搬出来的内容写回
resizeWorkspace(nw, nh)
S.layers.forEach((layer, i) => {
const tmp = staged[i]
try { layer.ctx.drawImage(tmp, 0, 0) } catch (e) { /* ignore */ }
tmp.width = 0
tmp.height = 0
// 像素已落在新坐标系的正确位置,几何元数据不能再参与二次定位;
// 图片源(image / sourceCanvas)尺寸是旧的,留着会让重绘错位,必须摘掉。
// 摘掉后这些层按「像素层」参与快照与恢复(见 vendor/layer-logic.js)。
layer.x = 0
layer.y = 0
layer.w = nw
layer.h = nh
layer.rotation = 0
layer.transformable = false
layer.image = null
layer.sourceCanvas = null
layer._srcBox = null
layer._bounds = undefined
})
// ⑤ 文字/形状按裁剪区域位移与缩放
S.textLayers = S.textLayers.map(t => ({
...t,
x: (t.x - sx) * scaleX,
@@ -295,31 +317,29 @@ import { disposeSelection } from './selection.js'
fontSize: t.fontSize * scaleX
}))
S.shapeLayers = S.shapeLayers.map(s => ({
...s,
...(s.type === 'pen' ? { pts: (s.pts || []).map(p => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : {
x1: (s.x1 - sx) * scaleX, y1: (s.y1 - sy) * scaleY,
x2: (s.x2 - sx) * scaleX, y2: (s.y2 - sy) * scaleY
}),
lw: Math.max(1, s.lw * (scaleX + scaleY) / 2)
}))
...s,
...(s.type === 'pen' ? { pts: (s.pts || []).map(p => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : {
x1: (s.x1 - sx) * scaleX, y1: (s.y1 - sy) * scaleY,
x2: (s.x2 - sx) * scaleX, y2: (s.y2 - sy) * scaleY
}),
lw: Math.max(1, s.lw * (scaleX + scaleY) / 2)
}))
S.selectedTextId = null
S.textDrag = null
S.selectedShapeId = null
S.shapeDrag = null
// 裁剪后 setupCanvas 会重建全部位图图层,旧 selectedLayerId 会指向已删除的 id
// 裁剪后图层 id 不变但几何全变,旧的选中 id 与拖拽中间态都要清
S.selectedLayerId = null
S.bitmapDrag = null
S.zoom = 1
setupCanvas(cropC)
S.history = []
S.redoStack = []
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
clearOverlay()
updateCropInfo()
// 尺寸/坐标系已变,统一重绘出口要在新画布上重建选区层与浮动条位置
if (S.renderAll) S.renderAll()
toast('已裁剪为 ' + nw + '×' + nh + '(Ctrl+Z 可撤销)', 'success')
}
export function cancelCrop() {
+199 -45
View File
@@ -231,14 +231,14 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false }
const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) }
const first = S.penPath.pts[0]
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)) {
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)) {
S.penPath.closed = true
S.penPath.nearStart = true
S.penPath.preview = null
commitPenPath()
} else {
S.penPath.pts.push(point)
renderObjects({ id: 'pen-preview', type: 'pen', pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(2, S.brushSize), fill: false, opacity: 1, visible: true })
renderObjects({ id: 'pen-preview', type: 'pen', pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: false, opacity: 1, visible: true })
}
return
}
@@ -423,7 +423,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔路径预览:更新悬停点与起点闭合提示 */
function onPenDrawMove(pos) {
if (S.penPath) { S.penPath.preview = pos; const first = S.penPath.pts[0]
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
S.penPath.nearStart = !!nearStart
renderObjects() }
}
@@ -436,8 +436,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
x1: S.startX, y1: S.startY,
x2: pos.x, y2: pos.y,
color: S.color,
lw: Math.max(2, S.brushSize),
lineWidth: Math.max(2, S.brushSize),
lw: Math.max(1, S.shapeLineWidth),
lineWidth: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
opacity: 1,
visible: true
@@ -635,7 +635,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
x1: S.startX, y1: S.startY,
x2: pos.x, y2: pos.y,
color: S.color,
lw: Math.max(2, S.brushSize),
lw: Math.max(1, S.shapeLineWidth),
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
opacity: 1,
visible: true,
@@ -799,32 +799,101 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
picker: '吸管', hand: '抓手', crop: '裁剪'
}
/** 选项栏只露当前工具 2–3 个参数;用独立控件,避免与右侧旧参数区抢 querySelector */
export function renderOptionBar() {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
let html = ''
if (S.tool === 'marquee') {
html = `<span class="iwb-opt-label">形状</span>
const OPT_HINTS = {
crop: '裁剪栏在画布下方;裁剪与选区互斥,确认后可 Ctrl+Z 撤销',
select: '点击选中元素,拖拽移动,手柄缩放',
picker: '点击画布取色,取完自动切回上一个工具',
hand: '拖拽平移画布;任意工具下按住空格也可以',
marquee: '拖出选区 → 操作条就在选区旁边',
lasso: '按住拖动画圈,松手闭合'
}
/** 滑杆 + 数字框共用同一 data-opt,两条输入路径都写回 S */
function rangeOpt(key, label, min, max, value, unit) {
return `<span class="iwb-opt-label">${label}</span>
<input type="range" class="iwb-opt-range" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">
<input type="number" class="iwb-opt-num" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">${unit ? `<span class="iwb-opt-unit">${unit}</span>` : ''}`
}
/** 每个工具只露最常用的 2–4 个参数,全部直接写回 S(右侧参数面板同步) */
function optionBarHTML(tool) {
if (tool === 'brush' || tool === 'eraser') {
return rangeOpt('brushSize', '大小', 1, 300, S.brushSize, '')
+ `<span class="iwb-opt-label">硬度</span>
<input type="range" class="iwb-opt-range" data-opt="brushHardness" min="0" max="100" step="1" value="${S.brushHardness}">
<span class="iwb-opt-val" data-opt-val="brushHardness">${S.brushHardness}</span>
<span class="iwb-opt-label">透明</span>
<input type="range" class="iwb-opt-range" data-opt="brushOpacity" min="5" max="100" step="1" value="${Math.round(S.brushOpacity * 100)}">
<span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>`
}
if (tool === 'rect' || tool === 'circle') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ `<span class="iwb-opt-label">样式</span>
<button class="iwb-opt-btn${S.rectFill ? '' : ' active'}" data-opt-toggle="stroke" data-value="stroke">描边</button>
<button class="iwb-opt-btn${S.rectFill ? ' active' : ''}" data-opt-toggle="fill" data-value="fill">实心</button>`
}
if (tool === 'arrow' || tool === 'pen') {
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
+ `<span class="iwb-opt-hint">${tool === 'pen' ? '逐点点击,点回起点闭合' : '拖出箭头,松手完成'}</span>`
}
if (tool === 'text') {
return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px')
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>'
}
if (tool === 'marquee') {
return `<span class="iwb-opt-label">形状</span>
<button class="iwb-opt-btn${S.selectionKind === 'rect' ? ' active' : ''}" data-opt="shape" data-value="rect">矩形</button>
<button class="iwb-opt-btn${S.selectionKind === 'ellipse' ? ' active' : ''}" data-opt="shape" data-value="ellipse">椭圆</button>
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
<span class="iwb-opt-hint">拖出选区 → 操作条就在选区旁边</span>`
} else if (S.tool === 'lasso') {
html = `<span class="iwb-opt-label">套索</span>
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
<span class="iwb-opt-hint">按住拖动画圈,松手闭合</span>`
} else {
const hints = {
crop: '裁剪栏在画布下方;裁剪与选区互斥',
brush: '选区激活时笔刷只画在选区内',
eraser: '橡皮只擦当前画笔目标图层(✎)',
select: '点击选中元素,拖拽移动,手柄缩放'
}
html = `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[S.tool] || S.tool}</span>
<span class="iwb-opt-hint">${hints[S.tool] || '选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层'}</span>`
<span class="iwb-opt-hint">${OPT_HINTS.marquee}</span>`
}
body.innerHTML = html
if (tool === 'lasso') {
return `<span class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</span>
<span class="iwb-opt-hint">${OPT_HINTS.lasso}</span>`
}
return `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[tool] || tool}</span>
<span class="iwb-opt-hint">${OPT_HINTS[tool] || '选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层'}</span>`
}
export function renderOptionBar(force) {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
// 工具没变就只同步数值:renderAll 每次操作都会走到这里,全量重建 innerHTML
// 会打断正在拖的滑杆和正在输入的数字框(静态审查 P2-11)。
if (!force && body.dataset.tool === S.tool) { syncOptionBar(); return }
body.dataset.tool = S.tool
body.innerHTML = optionBarHTML(S.tool)
syncOptionBar()
}
/** 只更新值与选中态,不重建 DOM —— 保证拖拽中的控件与输入焦点不被抢 */
export function syncOptionBar() {
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
if (!body) return
const val = (key) => {
if (key === 'brushSize') return S.brushSize
if (key === 'brushHardness') return S.brushHardness
if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100)
if (key === 'shapeLineWidth') return S.shapeLineWidth
if (key === 'textSize') return S.textSize
if (key === 'feather') return S.selectionFeather
return ''
}
body.querySelectorAll('input[data-opt]').forEach(el => {
if (document.activeElement === el) return // 正在拖/正在输入的不要被覆盖
const v = val(el.dataset.opt)
if (String(el.value) !== String(v)) el.value = v
})
body.querySelectorAll('[data-opt-val]').forEach(el => {
const v = val(el.dataset.optVal)
el.textContent = el.dataset.optVal === 'brushOpacity' ? v + '%' : v
})
body.querySelectorAll('[data-opt="shape"]').forEach(btn => {
btn.classList.toggle('active', S.selectionKind === btn.dataset.value)
})
body.querySelectorAll('[data-opt-toggle]').forEach(btn => {
btn.classList.toggle('active', !!S.rectFill === (btn.dataset.value === 'fill'))
})
}
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
@@ -847,6 +916,74 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
put('.iwb-editor-status-tool', TOOL_NAMES[S.tool] || S.tool)
}
// ---- 选项栏参数写回:单一真源是 S,右侧参数面板与画布随后同步 ----
let lwSnapDone = false
let textSnapDone = false
/** 线宽也作用到当前选中的形状:拖动中只重绘,松手才记一步历史 */
function applyShapeLineWidth(committed) {
const sh = getSelectedShape()
if (!sh || sh.locked) { lwSnapDone = false; return }
if (committed || !lwSnapDone) { saveSnapshot('线宽'); lwSnapDone = true }
sh.lw = S.shapeLineWidth
renderObjects()
if (committed) lwSnapDone = false
}
/** 字号也作用到当前选中的文字 */
function applyTextSize(committed) {
const t = getSelectedText()
if (!t || t.locked) { textSnapDone = false; return }
if (committed || !textSnapDone) { saveSnapshot('字号'); textSnapDone = true }
t.fontSize = S.textSize
renderObjects()
if (committed) textSnapDone = false
}
/** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个 */
function setShapeFill(fill) {
S.rectFill = !!fill
updateFillUI()
syncOptionBar()
const sh = getSelectedShape()
if (sh && (sh.type === 'rect' || sh.type === 'circle') && !sh.locked) {
saveSnapshot('填充')
sh.fill = S.rectFill
renderObjects()
}
}
function setOptionFromControl(el, committed) {
const key = el && el.dataset ? el.dataset.opt : ''
if (!key) return
const n = Math.round(Number(el.value))
const safe = Number.isFinite(n) ? n : 0
if (key === 'brushSize') {
S.brushSize = clamp(safe || 1, 1, 300)
updateBrushUI()
updateBrushParamUI()
} else if (key === 'brushHardness') {
S.brushHardness = clamp(safe, 0, 100)
updateBrushParamUI()
} else if (key === 'brushOpacity') {
S.brushOpacity = clamp(safe || 100, 5, 100) / 100
updateBrushParamUI()
if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity
} else if (key === 'shapeLineWidth') {
S.shapeLineWidth = clamp(safe || 1, 1, 60)
applyShapeLineWidth(committed)
} else if (key === 'textSize') {
S.textSize = clamp(safe || 32, 8, 400)
applyTextSize(committed)
} else if (key === 'feather') {
S.selectionFeather = clamp(safe, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
updateStatusbar()
}
syncOptionBar()
}
/** 更多菜单 / 面板收起 / 选项栏控件:只绑定一次,DOM 重绘不丢事件(委托) */
export function bindLiteUI() {
const root = runtime.el
@@ -907,23 +1044,25 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
const body = root.querySelector('.iwb-editor-optionbar-body')
if (body) {
body.addEventListener('mousedown', (e) => e.stopPropagation())
// 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径,
// committed 只决定「要不要顺手记一步历史」,不影响参数生效。
body.addEventListener('input', (e) => setOptionFromControl(e.target, false))
body.addEventListener('change', (e) => setOptionFromControl(e.target, true))
body.addEventListener('click', (e) => {
const btn = e.target.closest('[data-opt="shape"]')
if (!btn) return
e.stopPropagation()
S.selectionKind = btn.dataset.value === 'ellipse' ? 'ellipse' : 'rect'
renderOptionBar()
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
const shapeBtn = e.target.closest('[data-opt="shape"]')
if (shapeBtn) {
e.stopPropagation()
S.selectionKind = shapeBtn.dataset.value === 'ellipse' ? 'ellipse' : 'rect'
syncOptionBar()
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
return
}
const toggle = e.target.closest('[data-opt-toggle]')
if (toggle) {
e.stopPropagation()
setShapeFill(toggle.dataset.value === 'fill')
}
})
const onFeather = (e) => {
const input = e.target.closest('[data-opt="feather"]')
if (!input) return
S.selectionFeather = clamp(parseInt(input.value, 10) || 0, 0, 20)
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
updateStatusbar()
}
body.addEventListener('input', onFeather)
body.addEventListener('change', onFeather)
}
// 点画布 / 面板其它地方收起下拉。必须用捕获阶段:modal 自身有个
@@ -1277,7 +1416,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
function commitPenPath() {
if (!S.penPath || S.penPath.pts.length < 2) { S.penPath = null; renderObjects(); return }
saveSnapshot()
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(2, S.brushSize), fill: !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
S.shapeLayers.push(shape); selectUnit('shape', shape.id); S.penPath = null; renderObjects(); renderLayerPanel()
}
@@ -1452,9 +1591,24 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
S.drawCanvasCursor('crosshair')
}
/**
* 是否处于「正在输入文字」态 —— 只对**文字内容**输入框为真。
*
* v1.2 修正:原来任何 INPUT 都算打字,于是在选项栏的数字框(羽化/线宽/字号)
* 里输完值后,Ctrl+A、Ctrl+J、Delete、Esc 全被吞掉,表现成「快捷键突然没反应」。
* 参数控件里带修饰键的组合、Delete 与 Esc 一律放行给画布;单个字符仍然正常输入。
*/
function isTyping(e) {
const t = e.target
return t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA')
if (!t) return false
if (t.tagName === 'TEXTAREA') return true
if (t.tagName !== 'INPUT') return false
const cls = t.classList
if (cls && (cls.contains('iwb-editor-text-input') || cls.contains('iwb-editor-color-hex-input'))) return true
// 以下是参数控件(数字框 / 滑杆)
if (e.ctrlKey || e.metaKey || e.altKey) return false
if (e.key === 'Delete' || e.key === 'Escape') return false
return true
}
function onKeydown(e) {
+13 -1
View File
@@ -17,7 +17,7 @@ import {
createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer,
renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles
} from './layers.js'
import { setupCanvas } from './viewport.js'
import { resizeWorkspace, setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
@@ -160,6 +160,18 @@ import { toast } from './commands.js'
/** 恢复到指定状态(含图层增删) */
function restoreState(state) {
// v1.2:裁剪也进历史链,所以快照的画布尺寸可能与当前不同,必须先把尺寸复位。
// 尺寸一变,现有图层对象的像素缓冲已被 resizeWorkspace 清空、几何元数据也失效,
// 直接「复用现有图层再 putImageData」会让走过 redraw 路径的图片层彻底丢内容;
// 因此全部释放、让下面的「按快照重建」分支统一重建(它会按 bm 的 imageRef/sourceRef
// 选择 redraw 还是 pixels)。
if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) {
purgeVectorCanvases()
for (const l of S.layers) releaseLayer(l)
S.layers = []
resizeWorkspace(state.imgW, state.imgH)
}
purgeVectorCanvases()
for (const l of S.layers) l._bounds = undefined
+11 -1
View File
@@ -95,6 +95,8 @@ import { toast } from './commands.js'
S.prevTool = null
S.pickerComposite = null
S.rectFill = false
S.shapeLineWidth = 3
S.textSize = 32
S.cropConstraint = { type: 'free', ratio: 0, sizeW: 0, sizeH: 0 }
S.textLayers = []
S.selectedTextId = null
@@ -284,12 +286,20 @@ import { toast } from './commands.js'
tool: S.tool,
doc: { w: S.imgW, h: S.imgH },
layers: S.layers.map(l => ({ id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false })),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type })),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
selectedTextId: S.selectedTextId,
activeLayerId: S.activeLayerId,
selection: selectionInfo(),
toolOptions: {
brushSize: S.brushSize,
brushHardness: S.brushHardness,
brushOpacity: S.brushOpacity,
shapeLineWidth: S.shapeLineWidth,
textSize: S.textSize,
rectFill: S.rectFill
},
history: S.history.length,
historyLabels: S.history.map(s => s.__label || ''),
redo: S.redoStack.length,
+3 -3
View File
@@ -343,12 +343,12 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const ctx = S.overlayCtx
const pts = path.pts.slice()
const first = pts[0]
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.brushSize * 1.5)
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
if (path.preview) pts.push(nearStart ? first : path.preview)
ctx.save()
ctx.strokeStyle = S.color
ctx.fillStyle = nearStart ? 'rgba(232, 167, 53, 0.18)' : 'transparent'
ctx.lineWidth = Math.max(2, S.brushSize) / S.zoom
ctx.lineWidth = Math.max(1, S.shapeLineWidth) / S.zoom
ctx.setLineDash([8 / S.zoom, 5 / S.zoom])
ctx.beginPath()
ctx.moveTo(pts[0].x, pts[0].y)
@@ -604,7 +604,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
id: 't' + Date.now() + Math.floor(Math.random() * 1000),
x, y, text,
color: S.color,
fontSize: Math.max(16, S.brushSize * 6),
fontSize: Math.max(8, S.textSize),
opacity: 1,
visible: true,
locked: false,
+5 -1
View File
@@ -21,7 +21,11 @@
brushOpacity: 1, // 画笔透明度 0.05~1(一笔整体透明度,笔划内不叠加)
prevTool: null, // 吸管工具激活前的工具(取色后切回)
pickerComposite: null, // 吸管取样用的合成画布缓存(切工具/画布变化时失效)
rectFill: false, // 矩形是否实心填充
rectFill: false, // 矩形/圆形是否实心填充
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
textSize: 32, // 新建文字的字号 px
// 图层系统
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标)
+42
View File
@@ -105,6 +105,48 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
bindCanvasEvents()
}
/**
* 只调整画布尺寸与交互层,不重建图层(裁剪 / 撤销裁剪共用)。
*
* 与 setupCanvas 的分工:setupCanvas 会清空 S.layers 并新建「原图 + 画笔」两层,
* 那是「打开一张新图」的语义。裁剪只是在同一张图上换视窗,像素由调用方先搬好,
* 这里只负责尺寸、交互层、矢量层与视图基准,图层结构原样保留。
*
* ⚠️ 这里会把每个图层 canvas 的像素缓冲清空(canvas.width 赋值即重置),
* 调用方必须在调用前把像素复制出来,调用后写回。
*/
export function resizeWorkspace(w, h) {
S.imgW = Math.max(1, Math.round(w))
S.imgH = Math.max(1, Math.round(h))
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
}
purgeVectorCanvases()
for (const layer of S.layers) {
layer.canvas.width = S.imgW
layer.canvas.height = S.imgH
layer._bounds = undefined
}
S.pickerComposite = null
clearOverlay()
computeFit()
S.viewX = null
applyView()
renderObjects()
renderLayerPanel()
}
/** 计算「适应容器」的基准显示尺寸(不限制放大,小图也铺满) */
function computeFit() {
const availW = Math.max(50, S.canvasWrap.clientWidth - 48)
+1312 -1124
View File
File diff suppressed because it is too large. Load diff
+63 -2
View File
@@ -96,7 +96,7 @@ const boot = await page.evaluate((png) => {
window.__commands['annotate-selected'].run().catch(() => {})
return { version: window.__manifest.version, settingsSchema: Object.keys(window.__manifest.settings || {}) }
}, PNG)
check('产物可执行(循环打包未炸)', boot.version === '1.1.2', 'version=' + boot.version)
check('产物可执行(循环打包未炸)', boot.version === '1.2.0', 'version=' + boot.version)
check('manifest 声明输出预设设置项', boot.settingsSchema.includes('exportPreset') && boot.settingsSchema.includes('panelsCollapsed'), boot.settingsSchema.join(','))
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 15000 })
@@ -368,13 +368,20 @@ await drag2(box2.x + box2.width * 0.3, box2.y + box2.height * 0.3,
box2.x + box2.width * 0.6, box2.y + box2.height * 0.6)
const selF = (await dbg()).selection
await page.keyboard.press('Control+Shift+i')
const afterInvert = await dbg()
await page.keyboard.press('Delete')
const afterDel = await dbg()
const edgeAlphas = []
for (let dx = -6; dx <= 6; dx++) {
edgeAlphas.push((await pixel(Math.round(selF.x) + dx, Math.round(selF.y + selF.h / 2))).draw[3])
}
const edgeDbg = await dbg()
check('反选 + 羽化 6px:边界仍是渐变(羽化未因整幅掩膜失效)',
selF.feather === 6 && edgeAlphas.some(a => a > 0 && a < 255), JSON.stringify(edgeAlphas))
selF.feather === 6 && edgeAlphas.some(a => a > 0 && a < 255),
JSON.stringify(edgeAlphas) + ' feather=' + selF.feather + ' active=' + edgeDbg.activeLayerId +
' inv=' + (afterInvert.selection && afterInvert.selection.inverted) +
' hist=' + afterDel.historyLabels.slice(-2).join('/') +
' sel=' + JSON.stringify(afterDel.selection))
await page.keyboard.press('Control+z')
await page.keyboard.press('Control+d')
await page.locator('.iwb-editor-optionbar-body [data-opt="feather"]').fill('0')
@@ -436,6 +443,22 @@ check('裁剪后 Delete 不按旧 bbox 误擦(层数不变、底图仍有像
afterCropDelete.layers.length === cropped.layers.length && (await pixel(5, 5)).base[3] > 0 &&
afterCropDelete.selection === null)
// ---- 裁剪进历史链(v1.2 非破坏性):可撤销、可重做、不 flatten ----
const cropLayers = cropped.layers.map(l => l.id)
await page.keyboard.press('Control+z')
const undoneCrop = await dbg()
check('裁剪可 Ctrl+Z:画布尺寸与图层结构都回到裁剪前',
undoneCrop.doc.w === 96 && undoneCrop.doc.h === 64 &&
undoneCrop.layers.length === cropLayers.length &&
cropLayers.every(id => undoneCrop.layers.some(l => l.id === id)),
'doc=' + JSON.stringify(undoneCrop.doc) + ' layers=' + undoneCrop.layers.map(l => l.id).join(','))
check('裁剪撤销后底图像素完整回填', (await pixel(5, 5)).base[3] > 0)
await page.keyboard.press('Control+Shift+z')
const redoneCrop = await dbg()
check('裁剪可重做:尺寸回到裁剪后',
redoneCrop.doc.w === cropped.doc.w && redoneCrop.doc.h === cropped.doc.h,
JSON.stringify(redoneCrop.doc))
// ---- 还原原图的「尺寸复位」分支:必须走统一重绘,摘要/蚂蚁线才跟着走 ----
// (该分支会 setupCanvas + 清历史,此前只调 updateAllUI,摘要停留在裁剪后尺寸)
const cropSummary = await summaryText()
@@ -449,6 +472,44 @@ check('还原原图复位尺寸后:输出摘要即时跟随(不停留在裁
check('还原原图复位尺寸后蚂蚁线已停、选区已清',
restoredDoc.ants === false && !restoredDoc.selection)
// ---- v1.2 选项栏:按工具出参数,形状线宽与画笔解耦 ----
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
check('画笔选项栏:大小 / 硬度 / 透明三个参数都在',
(await page.locator('.iwb-editor-optionbar-body [data-opt="brushSize"]').count()) >= 2 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt="brushHardness"]').count()) === 1 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt="brushOpacity"]').count()) === 1)
const brushSizeBefore = (await dbg()).toolOptions.brushSize
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
check('矩形选项栏:线宽 + 描边/实心',
(await page.locator('.iwb-editor-optionbar-body [data-opt="shapeLineWidth"]').count()) >= 2 &&
(await page.locator('.iwb-editor-optionbar-body [data-opt-toggle="fill"]').count()) === 1)
await page.locator('.iwb-editor-optionbar-body input[type="number"][data-opt="shapeLineWidth"]').fill('12')
const optAfterLw = (await dbg()).toolOptions
check('选项栏改线宽:只改形状线宽,画笔大小不受影响(已解耦)',
optAfterLw.shapeLineWidth === 12 && optAfterLw.brushSize === brushSizeBefore,
JSON.stringify(optAfterLw))
const shapesBefore = (await dbg()).shapes.length
const liveBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await drag2(liveBox.x + liveBox.width * 0.2, liveBox.y + liveBox.height * 0.2,
liveBox.x + liveBox.width * 0.5, liveBox.y + liveBox.height * 0.5)
const shapesAfter = (await dbg()).shapes
check('新画的矩形直接用选项栏里的线宽 12',
shapesAfter.length === shapesBefore + 1 && shapesAfter[shapesAfter.length - 1].lw === 12,
JSON.stringify(shapesAfter.slice(-1)))
await page.keyboard.press('Control+z')
// isTyping 修正:参数数字框里按 Ctrl+A / Delete 应该走画布命令,而不是被当打字吞掉
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
await page.locator('.iwb-editor-optionbar-body input[data-opt="feather"]').fill('3')
await page.keyboard.press('Control+a')
const selAfterCtrlA = await dbg()
check('参数数字框里按 Ctrl+A 仍能全选(不再被当打字吞掉)',
Boolean(selAfterCtrlA.selection) &&
selAfterCtrlA.selection.w === selAfterCtrlA.doc.w && selAfterCtrlA.selection.h === selAfterCtrlA.doc.h,
JSON.stringify(selAfterCtrlA.selection))
await page.keyboard.press('Control+d')
// ---- Fix4:点「退出」必须结算宿主 Promise(glue.openEditor → onClose) ----
await page.locator('[data-action="cancel"]').click()
const openState = await poll(async () => page.evaluate(() => window.__openState))