Files
iwb-plugins-desktop/image-annotate/plugin/editor/index.js
T
qiqi 5f11e40f43 feat(image-annotate): v1.6.0 色板入工具栏 + 快速效果 + 画完回 V + 图层合并(补齐 1.3.0–1.6.0)
上一次提交停在 1.2.12,本次把 1.3.0 → 1.6.0 四个版本的源码一并归档。

v1.3.0 色板进工具栏 + 矢量/文字工具只负责创建
- 工具栏最左色点 → 弹层(前调色器、后颜色设置 + 推荐颜色)
  - 弹层必须挂 .iwb-editor-modal 下:工具栏是 overflow-x:auto、画布 wrap 是 overflow:clip,塞进去会被裁
  - applyColorChange 改 pointerdown 拍一次快照,修「拖调色器爆撤销栈」
  - 每次按下前从 S.color 重同步 hsv,修「点推荐色后再拖 SV 跳回红」
  - 外部点击改 document 捕获阶段监听(画布 mousedown preventDefault,冒泡收不到)
- onShapeMouseDown / onTextMouseDown 不再命中已有对象;setTool 的 keepSel 只剩 select|picker

v1.4.0 侧栏快速效果
- 6 个:反白(反相,非排版意义的黑底白字)/ 灰度 / 提亮 / 压暗 / 高对比 / 马赛克
- 目标是当前位图图层,标题右侧实时显示层名;不碰图层几何也不改 image
- 导入图片层先克隆栅格化成「xxx · 效果」层、原层 visible=false(直接改像素会被 redraw 冲掉)
- 撤销走快照,base 与画笔层走像素路径

v1.5.0 画完自动回 V,编辑统一走 V
- 图形/文字落笔完成即退出当前工具并切 V
- 钢笔改为只用 V 双击进节点编辑
- 双击判定改成自算 380ms 窗口:单击选中会重绘矢量画布,浏览器不再派发 dblclick

v1.6.0 笔刷环 + 图层合并
- 画笔用 [ / ] 调粗细时立刻刷新笔刷环(原来只在 mousemove 里 drawToolRing,键改后不动)
- 图层合并:⌘/Ctrl 点击多选后合并、⌘E 向下合并、⌘⇧E 合并可见(PS 语义)
  - 统一用 composeUnitsInto 合成并按结果重排 z,避免合并后像素为空
  - 隐藏层不参与且保留;矢量(文字/形状/钢笔)直接栅格化
  - 有 base 参与时写回 base(像素快照可逐像素撤销),否则新建位图层承载

harness 129 项全通。1.6.0 已发布到线上:
plugin-image-annotate.198a20e4d722.js / sha256-GYog5NcinRDM67in67JxJUtBhUPB2lfttM/kw9UHwFo=
2026-11-05 11:27:37 +08:00

345 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.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 })),
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
}