Files
iwb-plugins-desktop/image-annotate/plugin/editor/index.js
T
qiqi 3e76f2792e feat(image-annotate): v1.7.0 图层面板补齐(缩略图 / 重命名 / 不透明度)
按通读代码后定的顺序处理 P3 剩余项里最有价值的三条。

1) 不透明度真正可调
   opacity 字段一直在(合成/合并/导出/快照都读它),但面板没有任何控件能写它,
   roadmap 里标的「已有」与事实不符。现在选中层后在该项下方展开滑杆:
   - 位图走 canvas 的 CSS opacity(像素不动),导出/合并时乘 globalAlpha,所见即所得
   - 文字/形状改完重绘矢量层(不透明度已烘进像素,不能再叠 CSS)
   - input 第一次到达才拍快照,一次拖动只产生 1 条历史;双击滑杆复位 100%
   - 非 100% 且未选中的层在名字旁挂百分比角标

2) 缩略图 + 双击重命名
   - 22px 缩略图(canvas 44 设备像素),等比缩放居中;空图层透出类型图标兜底
   - 绘制合批 90ms,避免每次 renderLayerPanel 都重画几十张
   - 双击名字改名(Enter 提交 / Esc 放弃),改名期间禁用整项拖动

3) 顺手清理
   - 删除 .iwb-layer-color / .iwb-layer-width 两个永远看不见的死控件
     (CSS display:none !important 写了三遍),连同绑定与死样式
   - pasteImageFromUrl 的 window.alert 改 toast(阻塞弹窗在宿主里会卡整页)
   - resetState() 补清 layerMulti / hoverPos / lastClick / lastNameClick / altPicker

关键修正:矢量层不透明度只能乘一次。
drawVectorToCanvas / drawShape 已把 opacity 画进像素,getCompositeCanvas 与
composeUnitsInto 再乘 globalAlpha 就是双倍透明 —— 两处都改为只对位图乘。

验证:harness 133 项全通(新增 4 项)、validate 9/9、产物 331811 B。
harness 的版本断言改为读 package.json,不再硬编码。
2026-11-08 16:43:38 +08:00

356 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* IWB 图片编辑器 - 图层化裁剪与标注
* 独立模块,通过 window.__iwbEditor.open() 调用
* 接收 imageBase64,返回编辑后的 dataURL
*
* v2.0.0 特性:
* - 图层系统:位图图层动态管理(原图、画笔、导入图片),可调透明度、显隐、排序
* - 矢量对象(文字/形状)在图层面板中统一展示,z 序可调
* - 统一橡皮:一个橡皮擦除当前活跃位图图层,与画笔共用大小/透明度/软硬
* - 添加位图图层:支持导入新图片作为独立图层
* - 工具:选择 / 画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪
*
* 分层架构:
* - bitmap layers: 每个位图图层一个 canvas(动态创建/排序),CSS opacity 控制透明度
* - textCanvas: 矢量对象层(文字+形状),共享一个 canvas
* - strokeCanvas: 笔划预览层(一笔结束后合成进活跃图层)
* - overlayCanvas: 选中框/裁剪遮罩/笔刷预览
*/
/* index.js - 模块组装与对外接口
* 汇总各子模块,承载「打开编辑器 / 关闭 / 复原 / 输出」生命周期,
* 并把 window.__iwbEditor = { open, close, __stats } 挂到全局(对外唯一接口)。
* 注意:entries/content.js 必须先 import 本文件再 import content.js。
* 顶层只允许声明与这次 window 赋值,不调用其它模块的函数(避免循环 TDZ)。
*/
'use strict'
import { S, runtime } from './state.js'
import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotStats } from './history.js'
import { cancelImagePlacement } from './placement.js'
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput } from './objects.js'
import { setupCanvas } from './viewport.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { loadExportOptions, prepareOutput, downloadBlob, bindExportUI, renderExportUI } from './export.js'
import { toast } from './commands.js'
// ============ 打开编辑器 ============
export async function open(options) {
if (!options || !options.imageBase64) return
createEl()
S.callbacks = options
// 命令层 / 蚂蚁线的渲染出口走注入,避免新模块与 events.js 形成顶层求值循环
S.renderAll = renderAll
S.positionFloating = positionFloating
try {
const img = await loadImage(options.imageBase64)
S.imgW = img.naturalWidth || img.width
S.imgH = img.naturalHeight || img.height
S.originalImage = img
runtime.el.style.display = 'flex'
S.open = true
S.zoom = 1
setupCanvas(img)
resetState()
updateAllUI()
registerSelectionCommands()
loadExportOptions()
bindLiteUI()
bindFloating()
bindExportUI()
initPanels()
renderAll()
} catch (e) {
console.error('[IWB编辑器] 打开失败:', e)
if (runtime.el) runtime.el.style.display = 'none'
if (options.onError) options.onError(e.message)
} finally {
// 源图字符串只在解码这一刻有用(loadImage 内已转 blob URL)。
// 不丢的话 S.callbacks 会在整个编辑会话持有整份 dataURL(4K ≈44MB),
// 打开失败路径更是会一直挂到下次打开才被覆盖。
options.imageBase64 = null
}
}
function resetState() {
purgeVectorCanvases()
S.history = []
S.redoStack = []
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
S.isDrawing = false
S.panning = false
S.tool = 'brush'
S.color = '#ff4444'
S.brushSize = 3
S.brushHardness = 100
S.brushOpacity = 1
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
S.textDrag = null
S.textEditingId = null
S.shapeLayers = []
S.selectedShapeId = null
S.shapeDrag = null
S.penPath = null
S.penEditId = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
// 编辑器 DOM 复用,重开时旧的位图选中 id 指向已删除的图层,必须清掉
S.selectedLayerId = null
S.bitmapDrag = null
// 跨会话残留:多选合并集合、悬停点、双击判定都会指向上一张图的图层
S.layerMulti.length = 0
S.hoverPos = null
S.lastClick = null
S.lastNameClick = null
S.altPicker = false
S.zCounter = Math.max(S.layers.length - 1, 0)
S.placingImage = null
S.placingHandle = null
S.placingStart = null
const sizeToggle = runtime.el && runtime.el.querySelector('.iwb-editor-size-toggle')
if (sizeToggle) { sizeToggle.classList.remove('active'); sizeToggle.setAttribute('aria-pressed', 'false'); sizeToggle.textContent = '启用尺寸' }
// 重开时旧选区 / 蚂蚁线 / 浮动条不能残留
S.selection = null
S.marquee = null
S.lassoPts = null
S.interaction = 'idle'
S.lastExport = null
if (S._antFrame) { cancelAnimationFrame(S._antFrame); S._antFrame = 0 }
hideSelectionContext()
if (S.selectionCtx) renderSelection()
if (S.cursorCtx) {
const pad = S.overlayPad || 0
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad)
}
}
/** 命令层统一重绘出口:所有新操作的像素/UI/选区状态在这里对齐 */
function renderAll() {
if (!S.open || !runtime.el) return
renderObjects()
renderLayerPanel()
renderOptionBar()
updateStatusbar()
renderExportUI()
renderSelection()
syncAnts()
positionFloating()
}
/** 侧栏开合:记住上次选择,窄窗口默认收起(画布优先) */
function initPanels() {
if (!runtime.el) return
const st = S.callbacks && S.callbacks.settings
let saved = false
if (st && typeof st.get === 'function') { try { saved = !!st.get('panelsCollapsed') } catch (e) { /* ignore */ } }
const auto = (window.innerWidth || 1440) < 1100
runtime.el.classList.toggle('panels-collapsed', saved || auto)
}
/**
* 关闭编辑器。reason:'cancel'(用户点退出)| 'done'(导出成功后关闭)。
* 必须先通知宿主再置空 S.callbacks —— glue.js 的 openEditor() 只在
* onResult / onError / onClose 三处结算,「退出」曾经没有任何回调,宿主
* Promise 永远悬挂;回调异常不能阻断后面的内存释放。
*/
export function close(reason) {
const callbacks = S.callbacks
try {
if (callbacks && typeof callbacks.onClose === 'function') callbacks.onClose(reason || 'cancel')
} catch (e) {
console.error('[IWB编辑器] onClose 回调异常:', e)
}
if (runtime.el) {
hideTextInput()
runtime.el.style.display = 'none'
}
releaseEditorMemory()
S.open = false
S.callbacks = null
S.placingImage = null
S.placingHandle = null
S.placingStart = null
S.penPath = null
S.textEditingId = null
clearSelection()
hideSelectionContext()
disposeSelection()
}
/**
* 关闭即释放(对齐宿主「内存里不放大图」的模型):
* 此前 close() 只把遮罩 display:none,历史快照(≤128MB 的全幅 ImageData)、
* 各全幅图层/overlay canvas 的像素缓冲、原图 Image 与 base64 全部继续驻留 ——
* 编辑一张 4K 图后即使退出,堆里仍挂着 ~100MB,直到下次打开编辑器才被重建顶掉。
* 释放后下次 open() 由 setupCanvas + resetState 全量重建,无状态残留依赖。
*/
function releaseEditorMemory() {
// 1) 撤销/重做栈:像素快照是最大头
S.history = []
S.redoStack = []
// 2) 原图引用与吸管合成缓存(各为一张全幅位图)
S.originalImage = null
S.pickerComposite = null
// 3) 交互态复位:关闭后 window mouseup 等全局监听仍活着,靠标志位保证不落到绘制路径
S.isDrawing = false
S.panning = false
S.penDragPt = -1
S.penDragPending = null
S.placingImage = null
S.placingHandle = null
S.placingStart = null
// 4) 位图图层(含 sourceCanvas):置 0 释放像素缓冲并从 DOM 摘除;
// setupCanvas 依赖 S.layers 做清理,这里必须同步清空,避免下次打开残留旧 canvas
for (const layer of S.layers) {
try {
if (layer.sourceCanvas) { layer.sourceCanvas.width = 0; layer.sourceCanvas.height = 0 }
if (layer.canvas) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
layer.canvas.width = 0
layer.canvas.height = 0
}
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
}
S.layers = []
// 5) 工作 canvas:text / stroke / overlay(overlay 含 18% 交互边距,4K 图约 74MB)
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
try { if (c) { c.width = 0; c.height = 0 } } catch (e) { /* ignore */ }
}
// 6) 矢量对象的画布缓存
purgeVectorCanvases()
}
// ============ 输出 ============
/**
* 导出:合成 → PNG 字节 → onResult(out, mode) → close()。
* 用 toBlob 而非 toDataURL —— 编码结果落在浏览器 Blob 存储(堆外),
* 省掉全幅 base64 字符串(4K 图约 44MB JS 堆驻留);onResult 收到 Blob 或 dataURL 均可。
*/
/**
* 单张输出:prepareOutput() 负责合成 → 尺寸/背景 → 编码(含 ≤500KB 降质)。
* 一次只产出一个结果;download 只下载、不关编辑器、不回写宿主节点。
*/
export async function exportResult(mode) {
if (S.placingImage) cancelImagePlacement()
try {
const { blob } = await prepareOutput()
if (mode === 'download') {
downloadBlob(blob)
// download 不关编辑器:必须走一次统一重绘,摘要的「上次输出 …KB」才会更新
if (S.renderAll) S.renderAll()
return
}
if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode)
close('done')
} catch (e) {
console.error('[IWB编辑器] 导出失败:', e)
toast('导出失败:' + ((e && e.message) || '图片可能跨域'), 'error')
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('导出失败:' + ((e && e.message) || '图片跨域'))
}
}
// ============ 暴露接口 ============
/**
* 快照/历史开销观测口(性能回归与手测用):
* history / redo 当前栈深度与占用字节
* snapshots 快照次数
* getImageDataCalls 累计全幅像素读取次数(优化前后最直观的对比指标)
* bytesWritten 累计拍摄的像素字节数
*/
export const __stats = () => ({
history: S.history.length,
historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0),
redo: S.redoStack.length,
redoBytes: S.redoStack.reduce((n, s) => n + (s.__bytes || 0), 0),
maxEntries: HISTORY_MAX_ENTRIES,
maxBytes: HISTORY_MAX_BYTES,
historyBudget: historyBudgetBytes(),
...snapshotStats
})
/** 开发/回归观测口:本地探针与真站 e2e 用它断言图层、选区与像素,不参与业务逻辑 */
const __debug = () => ({
open: S.open,
tool: S.tool,
color: S.color,
altPicker: !!S.altPicker,
doc: { w: S.imgW, h: S.imgH },
zoom: S.zoom,
fit: { w: Math.round(S.fitW || 0), h: Math.round(S.fitH || 0) },
layers: S.layers.map(l => ({
id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false,
// 不透明度有两个面:数据字段(导出/合并用)与 CSS(屏幕上看到的),两者必须一致
opacity: l.opacity == null ? 1 : l.opacity,
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 })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
selectedTextId: S.selectedTextId,
penEditId: S.penEditId,
activeLayerId: S.activeLayerId,
selectedLayerId: S.selectedLayerId,
layerMulti: S.layerMulti.map(x => x.type + ':' + x.id),
selection: selectionInfo(),
toolOptions: {
brushSize: S.brushSize,
brushHardness: S.brushHardness,
brushOpacity: S.brushOpacity,
shapeLineWidth: S.shapeLineWidth,
textSize: S.textSize,
rectFill: S.rectFill,
penFill: S.penFill
},
history: S.history.length,
historyLabels: S.history.map(s => s.__label || ''),
redo: S.redoStack.length,
exportOptions: S.exportOptions ? { ...S.exportOptions } : null,
lastExport: S.lastExport ? { ...S.lastExport } : null,
interaction: S.interaction,
ants: !!S._antFrame,
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null,
pixel: (id, x, y) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx) return null
try { return Array.from(l.ctx.getImageData(Math.round(x), Math.round(y), 1, 1).data) } catch (e) { return null }
},
// 区域透明像素统计:断言「合并后两半都有内容」比逐点采样快一个量级
alphaIn: (id, x0, y0, x1, y1) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx) return 0
try {
const w = Math.max(1, Math.round(x1 - x0))
const h = Math.max(1, Math.round(y1 - y0))
const d = l.ctx.getImageData(Math.round(x0), Math.round(y0), w, h).data
let n = 0
for (let i = 3; i < d.length; i += 4) if (d[i] > 0) n++
return n
} catch (e) { return 0 }
}
})
window.__iwbEditor = {
open,
close,
__stats,
__debug
}