feat(image-annotate): 选区编辑 + 便利版 UI + 单张输出预设(1.1.0)
This commit is contained in:
1 parent
b9ace636ef
commit
662d7eae77
22 files changed
+3795
-343
No files matched your search
@@ -1338,3 +1338,141 @@
|
||||
.iwb-editor-layer-panel .iwb-layer-vis,
|
||||
.iwb-editor-layer-panel .iwb-layer-lock,
|
||||
.iwb-editor-layer-panel .iwb-layer-del { width: 22px; height: 22px; padding: 0; display: inline-flex; align-items: center; justify-content: center; }
|
||||
|
||||
/* ================================================================
|
||||
v1.1 便利版 UI(单张处理)
|
||||
只追加、不重写历史样式:旧规则里的魔数定位在这里统一覆盖。
|
||||
分区:顶栏 / 就地选项栏 / 竖工具栏 / 画布浮层 / 状态栏 / toast
|
||||
================================================================ */
|
||||
|
||||
/* ---- 顶栏:精简、一步可达 ---- */
|
||||
.iwb-editor-header { min-height: 44px; padding: 6px 12px; gap: 8px; }
|
||||
.iwb-editor-title em.iwb-editor-doc-size { font-style: normal; font-weight: 400; font-size: 11px; color: #7f849c; margin-left: 6px; }
|
||||
.iwb-editor-optionbar {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
height: 36px; min-height: 36px; padding: 0 12px;
|
||||
background: #202033; border-bottom: 1px solid #313244;
|
||||
color: #a6adc8; font-size: 12px;
|
||||
}
|
||||
.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-opt-label { color: #a6adc8; white-space: nowrap; }
|
||||
.iwb-opt-btn {
|
||||
background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;
|
||||
padding: 3px 9px; font-size: 12px; cursor: pointer;
|
||||
}
|
||||
.iwb-opt-btn:hover { background: #45475a; }
|
||||
.iwb-opt-btn.active { background: #4488ff; color: #fff; }
|
||||
.iwb-opt-num {
|
||||
width: 46px; padding: 2px 4px; background: #313244; color: #e8a735;
|
||||
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-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
.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 {
|
||||
background: #313244; color: #cdd6f4; border: 1px solid #45475a; border-radius: 6px;
|
||||
padding: 5px 10px; font-size: 12px; cursor: pointer; white-space: nowrap;
|
||||
}
|
||||
.iwb-editor-more-btn:hover, .iwb-editor-panel-toggle:hover, .iwb-editor-export-settings-btn:hover { background: #45475a; }
|
||||
.iwb-editor-panel-toggle { padding: 5px 8px; }
|
||||
.iwb-editor-export-summary { color: #e8a735; margin: 0 2px; }
|
||||
|
||||
.iwb-editor-more-menu, .iwb-editor-export-settings {
|
||||
display: none; position: absolute; top: 34px; z-index: 60;
|
||||
background: #252537; border: 1px solid #45475a; border-radius: 8px;
|
||||
padding: 6px; box-shadow: 0 10px 30px rgba(0,0,0,0.45);
|
||||
}
|
||||
.iwb-editor-more-menu { left: 0; width: 206px; flex-direction: column; gap: 2px; }
|
||||
.iwb-editor-more-menu.open, .iwb-editor-export-settings.open { display: flex; flex-direction: column; gap: 4px; }
|
||||
.iwb-editor-export-settings { right: 0; width: 268px; }
|
||||
.iwb-editor-more-menu button, .iwb-editor-export-row button {
|
||||
background: transparent; color: #cdd6f4; border: 0; border-radius: 5px;
|
||||
padding: 6px 8px; font-size: 12px; text-align: left; cursor: pointer; white-space: nowrap;
|
||||
}
|
||||
.iwb-editor-more-menu button:hover, .iwb-editor-export-row button:hover { background: #3b3d52; }
|
||||
.iwb-editor-more-menu kbd { float: right; color: #7f849c; font-size: 10px; }
|
||||
.iwb-editor-more-sep { height: 1px; background: #45475a; margin: 4px 0; }
|
||||
.iwb-editor-export-row { display: flex; align-items: center; gap: 4px; }
|
||||
.iwb-editor-export-row > span { width: 34px; flex: 0 0 34px; color: #7f849c; font-size: 11px; }
|
||||
.iwb-editor-export-row button { flex: 1 1 auto; text-align: center; background: #313244; }
|
||||
.iwb-editor-export-row button.active { background: #4488ff; color: #fff; }
|
||||
.iwb-editor-export-note { color: #7f849c; font-size: 11px; border-top: 1px solid #313244; padding-top: 6px; }
|
||||
.iwb-editor-btn-download { background: #1a7f37 !important; color: #fff !important; }
|
||||
.iwb-editor-btn-download:hover { background: #15803d !important; }
|
||||
|
||||
/* ---- 竖工具栏:真正固定在左侧,给 main 留出 56px ---- */
|
||||
.iwb-editor-header > .iwb-editor-tools {
|
||||
position: fixed !important; left: 8px !important; top: 112px !important;
|
||||
width: 40px !important; max-height: calc(100vh - 128px);
|
||||
flex-direction: column; padding: 5px !important; border-radius: 10px;
|
||||
overflow-y: auto; overflow-x: hidden; scrollbar-width: none; z-index: 50;
|
||||
}
|
||||
.iwb-editor-header > .iwb-editor-tools::-webkit-scrollbar { display: none; }
|
||||
.iwb-editor-header > .iwb-editor-tools .iwb-editor-tool,
|
||||
.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { width: 30px !important; height: 30px !important; min-width: 30px; flex: 0 0 auto; }
|
||||
.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider { width: 22px; height: 1px; margin: 3px 0; flex: 0 0 auto; }
|
||||
.iwb-editor-header > .iwb-editor-tools .iwb-editor-fill-btn { width: 30px !important; padding: 3px 0 !important; font-size: 10px; writing-mode: vertical-rl; }
|
||||
.iwb-editor-main { padding-left: 56px; }
|
||||
.iwb-editor-main > .iwb-editor-layer-panel { flex: 0 0 260px !important; min-width: 260px !important; width: 260px !important; }
|
||||
.iwb-editor-left { flex: 0 0 220px !important; min-width: 220px !important; width: 220px !important; }
|
||||
.iwb-editor-overlay.panels-collapsed .iwb-editor-layer-panel,
|
||||
.iwb-editor-overlay.panels-collapsed .iwb-editor-left { display: none !important; }
|
||||
.iwb-editor-zoom-hint { display: none !important; }
|
||||
|
||||
/* ---- 交互层:蚂蚁线 / 笔刷环各自独立,互不擦除 ---- */
|
||||
.iwb-editor-selection-overlay, .iwb-editor-cursor-overlay {
|
||||
position: absolute; top: 0; left: 0; display: block; pointer-events: none;
|
||||
background: transparent !important;
|
||||
}
|
||||
.iwb-editor-selection-overlay { z-index: 11; }
|
||||
.iwb-editor-cursor-overlay { z-index: 12; }
|
||||
|
||||
/* ---- 选区浮动操作条(体验后再定去留;纯视图,可随时替换) ---- */
|
||||
.iwb-editor-sel-bar {
|
||||
display: none; position: absolute; z-index: 30; align-items: center; gap: 4px;
|
||||
padding: 5px 6px; background: rgba(24,24,37,0.96);
|
||||
border: 1px solid #45475a; border-radius: 8px;
|
||||
box-shadow: 0 8px 26px rgba(0,0,0,0.45); white-space: nowrap;
|
||||
}
|
||||
.iwb-editor-sel-bar.as-menu { border-color: #4488ff; }
|
||||
.iwb-editor-sel-bar .iwb-editor-sel-info {
|
||||
color: #7f849c; font-size: 11px; padding: 0 6px;
|
||||
border-right: 1px solid #45475a; margin-right: 2px; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.iwb-editor-sel-bar button {
|
||||
background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;
|
||||
padding: 4px 8px; font-size: 12px; cursor: pointer;
|
||||
}
|
||||
.iwb-editor-sel-bar button:hover:not(:disabled) { background: #4488ff; color: #fff; }
|
||||
.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]:hover:not(:disabled) { background: #cf222e; }
|
||||
.iwb-editor-sel-bar button:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
|
||||
/* ---- 状态栏 / toast ---- */
|
||||
.iwb-editor-statusbar {
|
||||
display: flex; align-items: center; gap: 14px;
|
||||
height: 26px; min-height: 26px; padding: 0 12px;
|
||||
background: #181825; border-top: 1px solid #313244;
|
||||
color: #a6adc8; font-size: 11px; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.iwb-editor-statusbar span + span { border-left: 1px solid #313244; padding-left: 14px; }
|
||||
.iwb-editor-status-tool { margin-left: auto; color: #e8a735; }
|
||||
.iwb-editor-toast {
|
||||
position: fixed; left: 50%; bottom: 46px; z-index: 1000000;
|
||||
transform: translate(-50%, 12px); opacity: 0; pointer-events: none;
|
||||
transition: opacity 0.2s, transform 0.2s;
|
||||
background: #313244; color: #cdd6f4; padding: 8px 14px; border-radius: 8px;
|
||||
font-size: 12px; max-width: 80vw; box-shadow: 0 8px 26px rgba(0,0,0,0.45);
|
||||
}
|
||||
.iwb-editor-toast.show { opacity: 1; transform: translate(-50%, 0); }
|
||||
.iwb-editor-toast-success { background: #1a7f37; color: #fff; }
|
||||
.iwb-editor-toast-error { background: #cf222e; color: #fff; }
|
||||
.iwb-editor-toast-warn { background: #b06a00; color: #fff; }
|
||||
.iwb-editor-toast-info { background: #2f6fed; color: #fff; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.iwb-opt-hint, .iwb-editor-optionbar-tip { display: none; }
|
||||
.iwb-editor-export-actions .iwb-editor-btn-cancel { display: none; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/* commands.js - 统一命令层(P0 地基)
|
||||
*
|
||||
* 浮动操作条 / 右键菜单 / 快捷键是三个「视图」,都必须走同一条 execute():
|
||||
* execute(label, mutator) → 前置守卫 → 快照(label) → mutator 只改状态 → 统一重绘 → 记历史
|
||||
* 这样所有新操作自动获得 Ctrl+Z / Ctrl+Shift+Z,也不会出现三套逻辑各修一遍。
|
||||
*
|
||||
* 旧标注工具仍直接调用 history.saveSnapshot()(行为不变、仍可撤销),
|
||||
* 新功能(选区、还原原图、输出)一律走本模块;后续可渐进迁移旧入口。
|
||||
*
|
||||
* 循环依赖规避:本文件顶层不 import 任何渲染模块。渲染出口由 index.js
|
||||
* 在 open() 时注入 S.renderAll,命令注册表由各功能模块在顶层 defineCommand()。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { S, runtime } from './state.js'
|
||||
import { saveSnapshot } from './history.js'
|
||||
|
||||
/** 命令注册表:name → { label, enabled?, run } */
|
||||
export const COMMANDS = Object.create(null)
|
||||
|
||||
export function defineCommand(name, def) {
|
||||
COMMANDS[name] = Object.assign({ label: name }, def || {})
|
||||
}
|
||||
|
||||
/** 统一变更入口。mutator 抛错时回滚刚压入的快照,避免留下「空撤销步」。 */
|
||||
export function execute(label, mutator) {
|
||||
const before = S.history.length
|
||||
saveSnapshot(label)
|
||||
let result
|
||||
try {
|
||||
result = mutator()
|
||||
} catch (err) {
|
||||
if (S.history.length === before + 1) S.history.pop()
|
||||
throw err
|
||||
}
|
||||
if (S.renderAll) S.renderAll()
|
||||
return result
|
||||
}
|
||||
|
||||
/** 三入口共用的命令调用;enabled() 返回 false 时给 toast 而不是静默失败。 */
|
||||
export function runCommand(name) {
|
||||
const def = COMMANDS[name]
|
||||
if (!def) return false
|
||||
if (typeof def.enabled === 'function' && !def.enabled()) {
|
||||
toast(def.hint || '当前状态下不可用', 'warn')
|
||||
return false
|
||||
}
|
||||
const args = Array.prototype.slice.call(arguments, 1)
|
||||
try {
|
||||
// 纯视图命令(全选 / 反选 / 取消选区)不产生撤销步
|
||||
if (def.view) {
|
||||
const r = def.run.apply(null, args)
|
||||
if (S.renderAll) S.renderAll()
|
||||
return r
|
||||
}
|
||||
return execute(def.label, () => def.run.apply(null, args))
|
||||
} catch (err) {
|
||||
console.error('[IWB编辑器] 命令执行失败:' + name, err)
|
||||
toast('操作失败:' + ((err && err.message) || name), 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 轻量 toast:取代 window.alert / window.confirm,不打断画布操作 */
|
||||
let toastTimer = null
|
||||
export function toast(message, kind) {
|
||||
const el = runtime.el && runtime.el.querySelector('.iwb-editor-toast')
|
||||
if (!el) return
|
||||
el.textContent = String(message || '')
|
||||
el.className = 'iwb-editor-toast iwb-editor-toast-' + (kind || 'info') + ' show'
|
||||
if (toastTimer) clearTimeout(toastTimer)
|
||||
toastTimer = setTimeout(() => { el.classList.remove('show'); toastTimer = null }, 2600)
|
||||
}
|
||||
@@ -19,16 +19,34 @@ import { bindEvents } from './events.js'
|
||||
runtime.el.innerHTML = `
|
||||
<div class="iwb-editor-modal">
|
||||
<div class="iwb-editor-header">
|
||||
<span class="iwb-editor-title">图片编辑</span>
|
||||
<span class="iwb-editor-title">图片编辑 <em class="iwb-editor-doc-size">—</em></span>
|
||||
<div class="iwb-editor-history">
|
||||
<button class="iwb-editor-action" data-action="undo" title="撤销 (Ctrl+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></button>
|
||||
<button class="iwb-editor-action" data-action="redo" title="重做 (Ctrl+Shift+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg></button>
|
||||
<button class="iwb-editor-action" data-action="reset" title="清空标注"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
|
||||
<button class="iwb-editor-action iwb-editor-action-restore" data-action="restore" title="复原原始图(撤销所有编辑)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></button>
|
||||
<button class="iwb-editor-action iwb-editor-action-reset" data-action="reset" title="还原原图:删掉所有标注/图层,回到打开时的样子(Ctrl+Z 可撤销)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
|
||||
</div>
|
||||
<div class="iwb-editor-more-wrap">
|
||||
<button class="iwb-editor-more-btn" data-action="toggleMore" aria-expanded="false">更多 ▾</button>
|
||||
<div class="iwb-editor-more-menu">
|
||||
<button data-more="sel.all">全选 <kbd>Ctrl+A</kbd></button>
|
||||
<button data-more="sel.invert">反选 <kbd>Ctrl+Shift+I</kbd></button>
|
||||
<button data-more="sel.none">取消选区 <kbd>Esc</kbd></button>
|
||||
<span class="iwb-editor-more-sep"></span>
|
||||
<button data-more="addBlankLayer">新建空白图层</button>
|
||||
<button data-more="addBitmapLayer">导入图片为图层</button>
|
||||
<button data-more="zoomFit">适应窗口</button>
|
||||
<button data-more="reset">还原原图</button>
|
||||
<span class="iwb-editor-more-sep"></span>
|
||||
<button data-action="togglePanels">收起 / 展开侧栏</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="iwb-editor-panel-toggle" data-action="togglePanels" title="收起 / 展开侧栏(画布优先)">⇥</button>
|
||||
<div class="iwb-editor-tools">
|
||||
<button class="iwb-editor-tool" data-tool="select" title="选择/移动:点击元素选中,拖拽移动,手柄调整大小,双击文字改内容"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/></svg></button>
|
||||
|
||||
<button class="iwb-editor-tool" data-tool="marquee" title="框选:拖出矩形/椭圆选区,松手后旁边出现操作条(M)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4 3"><rect x="3" y="4" width="18" height="16" rx="1"/></svg></button>
|
||||
<button class="iwb-editor-tool" data-tool="lasso" title="套索:按住拖动自由圈选,松手闭合(L)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12c0-4 3.6-7 8-7s8 3 8 7-3.6 7-8 7c-2 0-3.8-.6-5.2-1.6"/><path d="M6.8 17.4 4 20l1.2-3.2"/><circle cx="20" cy="19" r="2"/></svg></button>
|
||||
|
||||
<button class="iwb-editor-tool active" data-tool="brush" title="画笔"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg></button>
|
||||
|
||||
<button class="iwb-editor-tool" data-tool="eraser" title="橡皮:擦除当前活跃图层的内容(画笔标注或原图),与画笔共用大小/硬度/透明度"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg></button>
|
||||
@@ -58,11 +76,36 @@ import { bindEvents } from './events.js'
|
||||
<span class="iwb-editor-divider"></span>
|
||||
|
||||
<div class="iwb-editor-export-actions">
|
||||
<div class="iwb-editor-export-settings-wrap">
|
||||
<button class="iwb-editor-export-settings-btn" data-action="toggleExportSettings" aria-expanded="false">输出 <span class="iwb-editor-export-summary">原尺寸 PNG</span> ▾</button>
|
||||
<div class="iwb-editor-export-settings">
|
||||
<div class="iwb-editor-export-row"><span>预设</span>
|
||||
<button data-export-key="preset" data-export-value="original">原尺寸</button>
|
||||
<button data-export-key="preset" data-export-value="ecom800">电商 800² ≤500KB</button>
|
||||
</div>
|
||||
<div class="iwb-editor-export-row"><span>格式</span>
|
||||
<button data-export-key="format" data-export-value="png">PNG</button>
|
||||
<button data-export-key="format" data-export-value="jpeg">JPG</button>
|
||||
<button data-export-key="format" data-export-value="webp">WebP</button>
|
||||
</div>
|
||||
<div class="iwb-editor-export-row"><span>背景</span>
|
||||
<button data-export-key="bg" data-export-value="transparent">透明</button>
|
||||
<button data-export-key="bg" data-export-value="white">白底</button>
|
||||
</div>
|
||||
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="下载当前这一张(不关闭编辑器)">下载</button>
|
||||
<button class="iwb-editor-btn iwb-editor-btn-new" data-action="newNode">新建</button>
|
||||
<button class="iwb-editor-btn iwb-editor-btn-replace" data-action="replace">覆盖</button>
|
||||
<button class="iwb-editor-btn iwb-editor-btn-cancel" data-action="cancel">退出</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-editor-optionbar">
|
||||
<span class="iwb-editor-optionbar-label">工具选项</span>
|
||||
<div class="iwb-editor-optionbar-body"></div>
|
||||
<span class="iwb-editor-optionbar-tip">选区操作也可以右键,或用 Ctrl+J / Delete / Esc</span>
|
||||
</div>
|
||||
<div class="iwb-editor-main">
|
||||
|
||||
<div class="iwb-editor-layer-panel">
|
||||
@@ -90,6 +133,8 @@ import { bindEvents } from './events.js'
|
||||
<canvas class="iwb-editor-stroke"></canvas>
|
||||
<canvas class="iwb-editor-text"></canvas>
|
||||
<canvas class="iwb-editor-crop-overlay"></canvas>
|
||||
<canvas class="iwb-editor-selection-overlay"></canvas>
|
||||
<canvas class="iwb-editor-cursor-overlay"></canvas>
|
||||
</div>
|
||||
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消">
|
||||
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
|
||||
@@ -116,6 +161,16 @@ import { bindEvents } from './events.js'
|
||||
<button class="iwb-editor-crop-cancel" data-action="cancelCrop">✗ 取消</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-editor-sel-bar">
|
||||
<span class="iwb-editor-sel-info">未框选</span>
|
||||
<button data-sel-cmd="sel.copy" data-needs-sel="1" title="把当前图层选区复制为新图层 (Ctrl+J)">复制</button>
|
||||
<button data-sel-cmd="sel.cut" data-needs-sel="1" title="剪切到新图层 (Ctrl+X)">剪切</button>
|
||||
<button data-sel-cmd="sel.delete" data-needs-sel="1" title="只清除当前图层选区内容 (Delete)">删除</button>
|
||||
<button data-sel-cmd="sel.fill" data-needs-sel="1" title="用当前颜色填充选区">填充</button>
|
||||
<button data-sel-cmd="sel.invert" data-needs-sel="1" title="反选 (Ctrl+Shift+I)">反选</button>
|
||||
<button data-sel-cmd="sel.all" title="全选 (Ctrl+A)">全选</button>
|
||||
<button data-sel-cmd="sel.none" title="取消选区 (Esc / Ctrl+D)">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
|
||||
|
||||
@@ -161,6 +216,15 @@ import { bindEvents } from './events.js'
|
||||
<div class="iwb-editor-footer">
|
||||
|
||||
</div>
|
||||
<div class="iwb-editor-statusbar">
|
||||
<span class="iwb-editor-status-zoom">100%</span>
|
||||
<span class="iwb-editor-status-size">—</span>
|
||||
<span class="iwb-editor-status-pos">x — y —</span>
|
||||
<span class="iwb-editor-status-sel">无选区</span>
|
||||
<span class="iwb-editor-status-layer">当前层:画笔标注</span>
|
||||
<span class="iwb-editor-status-tool">画笔</span>
|
||||
</div>
|
||||
<div class="iwb-editor-toast" role="status" aria-live="polite"></div>
|
||||
</div>
|
||||
`
|
||||
document.body.appendChild(runtime.el)
|
||||
@@ -171,9 +235,13 @@ import { bindEvents } from './events.js'
|
||||
S.textCanvas = runtime.el.querySelector('.iwb-editor-text')
|
||||
S.strokeCanvas = runtime.el.querySelector('.iwb-editor-stroke')
|
||||
S.overlayCanvas = runtime.el.querySelector('.iwb-editor-crop-overlay')
|
||||
S.selectionCanvas = runtime.el.querySelector('.iwb-editor-selection-overlay')
|
||||
S.cursorCanvas = runtime.el.querySelector('.iwb-editor-cursor-overlay')
|
||||
S.textCtx = S.textCanvas.getContext('2d')
|
||||
S.strokeCtx = S.strokeCanvas.getContext('2d')
|
||||
S.overlayCtx = S.overlayCanvas.getContext('2d')
|
||||
S.selectionCtx = S.selectionCanvas.getContext('2d')
|
||||
S.cursorCtx = S.cursorCanvas.getContext('2d')
|
||||
|
||||
bindEvents()
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@
|
||||
import { S, ZOOM_STEP, runtime } from './state.js'
|
||||
import { ROT_CURSOR, clamp, getPos, isOverRotationHandle, setView, setZoomFit, zoomStep } from './viewport.js'
|
||||
import { addBitmapLayer, addBlankLayer, applyBitmapDrag, beginBitmapDrag, clearSelection, getActiveCtx, hitBitmapHandle, removeVecCanvas, renderLayerPanel } from './layers.js'
|
||||
import { applyColorChange, beginStroke, drawToolRing, endStroke, eraseSegment, exitPicker, hidePickerTip, sampleColor, setTool, showPickerTip, strokeSegment } from './tools.js'
|
||||
import { applyColorChange, beginStroke, clearToolRing, drawToolRing, endStroke, eraseSegment, exitPicker, hidePickerTip, sampleColor, setTool, showPickerTip, strokeSegment } from './tools.js'
|
||||
import { beginMarquee, updateMarquee, endMarquee, beginLasso, updateLasso, endLasso, clearMarquee, syncAnts, renderSelection } from './selection.js'
|
||||
import { runCommand, toast } from './commands.js'
|
||||
import { showSelectionContext, hideSelectionContext } from './floating.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, selectUnit, shapeBounds, showTextInput } from './objects.js'
|
||||
import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitPlacementHandle, insidePlacementRect, resizePlacement } from './placement.js'
|
||||
import { close, exportResult } from './index.js'
|
||||
import { loadImage } from './dom.js'
|
||||
import { pushHistory, redo, resetDraw, restoreOriginal, saveSnapshot, snapshotState, undo } from './history.js'
|
||||
import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js'
|
||||
import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
|
||||
|
||||
@@ -54,6 +57,11 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
const pos = getPos(e)
|
||||
S.startX = pos.x
|
||||
S.startY = pos.y
|
||||
hideSelectionContext()
|
||||
|
||||
// 选区工具:拉框 / 套索期间独占交互,不与选择/绘制/裁剪分支纠缠
|
||||
if (S.tool === 'marquee') { beginMarquee(pos); return }
|
||||
if (S.tool === 'lasso') { beginLasso(pos); return }
|
||||
|
||||
// 钢笔节点编辑优先:点节点/点边直接接管;点空白退出编辑后继续走下方工具逻辑
|
||||
if ((S.tool === 'select' || S.tool === 'pen')) {
|
||||
@@ -278,6 +286,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
onPanMouseMove(e); return
|
||||
}
|
||||
const pos0 = getPos(e)
|
||||
if (S.marquee) { updateMarquee(pos0); return }
|
||||
if (S.lassoPts) { updateLasso(pos0); return }
|
||||
if (S.bitmapDrag) {
|
||||
onBitmapDragMouseMove(pos0); return
|
||||
}
|
||||
@@ -468,6 +478,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
}
|
||||
|
||||
function onMouseUp(e) {
|
||||
if (S.marquee) { endMarquee(); return }
|
||||
if (S.lassoPts) { endLasso(); return }
|
||||
if (S.penDragPt >= 0) {
|
||||
onPenEditMouseUp(); return
|
||||
}
|
||||
@@ -674,6 +686,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
export function updateZoomUI() {
|
||||
const val = runtime.el.querySelector('.iwb-editor-zoom-val')
|
||||
if (val) val.textContent = Math.round(S.zoom * 100) + '%'
|
||||
updateStatusbar()
|
||||
}
|
||||
|
||||
export function updateToolUI() {
|
||||
@@ -681,6 +694,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
btn.classList.toggle('active', btn.dataset.tool === S.tool)
|
||||
})
|
||||
updateCursor()
|
||||
renderOptionBar()
|
||||
updateStatusbar()
|
||||
}
|
||||
|
||||
export function updateCursor() {
|
||||
@@ -776,6 +791,149 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
})
|
||||
}
|
||||
|
||||
// ============ 便利版 UI:就地选项栏 / 状态栏 / 更多菜单 ============
|
||||
|
||||
const TOOL_NAMES = {
|
||||
select: '选择 / 移动', marquee: '框选', lasso: '套索', brush: '画笔', eraser: '橡皮',
|
||||
pen: '钢笔', text: '文字', rect: '矩形', circle: '圆形', arrow: '箭头',
|
||||
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>
|
||||
<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>`
|
||||
}
|
||||
body.innerHTML = html
|
||||
}
|
||||
|
||||
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
|
||||
export function updateStatusbar() {
|
||||
if (!runtime.el) return
|
||||
const put = (sel, text) => {
|
||||
const el = runtime.el.querySelector(sel)
|
||||
if (el && el.textContent !== text) el.textContent = text
|
||||
}
|
||||
put('.iwb-editor-status-zoom', Math.round(S.zoom * 100) + '%')
|
||||
put('.iwb-editor-status-size', S.imgW + '×' + S.imgH)
|
||||
const p = S.lastPos
|
||||
put('.iwb-editor-status-pos', p ? ('x ' + Math.round(p.x) + ' y ' + Math.round(p.y)) : 'x — y —')
|
||||
const sel = S.selection && S.selection.active ? S.selection : null
|
||||
put('.iwb-editor-status-sel', sel
|
||||
? '选区 ' + Math.round(sel.bbox.w) + '×' + Math.round(sel.bbox.h) + (sel.feather ? ' · 羽化 ' + sel.feather : '') + (sel.inverted ? ' · 反选' : '')
|
||||
: '无选区')
|
||||
const layer = S.layers.find(l => l.id === S.activeLayerId)
|
||||
put('.iwb-editor-status-layer', '当前层:' + (layer ? layer.name : '—'))
|
||||
put('.iwb-editor-status-tool', TOOL_NAMES[S.tool] || S.tool)
|
||||
}
|
||||
|
||||
/** 更多菜单 / 面板收起 / 选项栏控件:只绑定一次,DOM 重绘不丢事件(委托) */
|
||||
export function bindLiteUI() {
|
||||
const root = runtime.el
|
||||
if (!root || root.dataset.liteBound === '1') return
|
||||
root.dataset.liteBound = '1'
|
||||
|
||||
const moreBtn = root.querySelector('[data-action="toggleMore"]')
|
||||
const moreMenu = root.querySelector('.iwb-editor-more-menu')
|
||||
const closeMenus = () => {
|
||||
if (moreMenu) moreMenu.classList.remove('open')
|
||||
if (moreBtn) moreBtn.setAttribute('aria-expanded', 'false')
|
||||
const panel = root.querySelector('.iwb-editor-export-settings')
|
||||
if (panel) panel.classList.remove('open')
|
||||
const toggle = root.querySelector('[data-action="toggleExportSettings"]')
|
||||
if (toggle) toggle.setAttribute('aria-expanded', 'false')
|
||||
}
|
||||
if (moreBtn && moreMenu) {
|
||||
moreBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
moreBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const open = moreMenu.classList.toggle('open')
|
||||
moreBtn.setAttribute('aria-expanded', String(open))
|
||||
})
|
||||
}
|
||||
if (moreMenu) {
|
||||
moreMenu.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
moreMenu.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button')
|
||||
if (!btn) return
|
||||
e.stopPropagation()
|
||||
const key = btn.dataset.more
|
||||
if (key && key.indexOf('sel.') === 0) runCommand(key)
|
||||
else if (key === 'addBlankLayer') addBlankLayer()
|
||||
else if (key === 'addBitmapLayer') {
|
||||
const b = root.querySelector('.iwb-editor-layer-add-btn[data-action="addBitmapLayer"]')
|
||||
if (b) b.click()
|
||||
} else if (key === 'zoomFit') setZoomFit()
|
||||
else if (key === 'reset') restoreAll()
|
||||
closeMenus()
|
||||
})
|
||||
}
|
||||
|
||||
root.querySelectorAll('[data-action="togglePanels"]').forEach(btn => {
|
||||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const collapsed = !root.classList.contains('panels-collapsed')
|
||||
root.classList.toggle('panels-collapsed', collapsed)
|
||||
const st = S.callbacks && S.callbacks.settings
|
||||
if (st && typeof st.set === 'function') {
|
||||
try { st.set('panelsCollapsed', collapsed) } catch (err) { /* ignore */ }
|
||||
}
|
||||
toast(collapsed ? '侧栏已收起' : '侧栏已展开', 'info')
|
||||
closeMenus()
|
||||
})
|
||||
})
|
||||
|
||||
const body = root.querySelector('.iwb-editor-optionbar-body')
|
||||
if (body) {
|
||||
body.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
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 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 自身有个
|
||||
// mousedown stopPropagation(阻止宿主抢事件),冒泡阶段收不到。
|
||||
const modal = root.querySelector('.iwb-editor-modal') || root
|
||||
modal.addEventListener('mousedown', (e) => {
|
||||
if (!e.target.closest('.iwb-editor-more-wrap') && !e.target.closest('.iwb-editor-export-settings-wrap')) closeMenus()
|
||||
}, true)
|
||||
}
|
||||
|
||||
// ============ 事件绑定 ============
|
||||
/**
|
||||
* 安全绑定:选择器找不到元素时只告警一次、不抛异常。
|
||||
@@ -1072,6 +1230,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
function bindExportActions() {
|
||||
// 底部
|
||||
bindIf('[data-action="cancel"]', 'click', close)
|
||||
bindIf('[data-action="download"]', 'click', () => exportResult('download'))
|
||||
bindIf('[data-action="newNode"]', 'click', () => exportResult('newNode'))
|
||||
bindIf('[data-action="replace"]', 'click', () => exportResult('replace'))
|
||||
}
|
||||
@@ -1132,10 +1291,13 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
S.canvasStack.addEventListener('mousemove', onMouseMove)
|
||||
S.canvasStack.addEventListener('mousemove', onCanvasHover)
|
||||
window.addEventListener('mouseup', onMouseUp)
|
||||
S.canvasStack.addEventListener('contextmenu', (e) => e.preventDefault())
|
||||
S.canvasStack.addEventListener('contextmenu', (e) => {
|
||||
e.preventDefault()
|
||||
if (S.open && !S.placingImage) showSelectionContext(e)
|
||||
})
|
||||
S.canvasStack.addEventListener('mouseleave', () => {
|
||||
if (S.placingImage) return
|
||||
if ((S.tool === 'brush' || S.tool === 'eraser') && !S.isDrawing) clearOverlay()
|
||||
if ((S.tool === 'brush' || S.tool === 'eraser') && !S.isDrawing) clearToolRing()
|
||||
if (S.tool === 'picker') hidePickerTip()
|
||||
})
|
||||
|
||||
@@ -1196,6 +1358,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
/** 悬停分发表:各工具的光标与预览(编排器负责前置守卫与旋转手柄优先) */
|
||||
const HOVER_HANDLERS = {
|
||||
select: onHoverSelect,
|
||||
marquee: onHoverCrosshair,
|
||||
lasso: onHoverCrosshair,
|
||||
picker: onHoverPicker,
|
||||
hand: onHoverHand,
|
||||
brush: onHoverBrushRing,
|
||||
@@ -1213,6 +1377,10 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (S.panning || S.spaceDown) return
|
||||
if (S.isDrawing || S.textDrag || S.shapeDrag) return
|
||||
const p = getPos(e)
|
||||
if (!S.lastPos || Math.abs(p.x - S.lastPos.x) > 0.5 || Math.abs(p.y - S.lastPos.y) > 0.5) {
|
||||
S.lastPos = p
|
||||
updateStatusbar()
|
||||
}
|
||||
if (isOverRotationHandle(p)) { S.drawCanvasCursor(ROT_CURSOR); return }
|
||||
const handler = Object.prototype.hasOwnProperty.call(HOVER_HANDLERS, S.tool) ? HOVER_HANDLERS[S.tool] : null
|
||||
if (handler) handler(p, e)
|
||||
@@ -1300,6 +1468,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (e.key === 'Enter' && S.tool === 'pen' && S.penPath) { e.preventDefault(); commitPenPath(); return }
|
||||
if (e.key === 'Escape') {
|
||||
if (isTyping(e)) { hideTextInput(); return }
|
||||
// 选区优先:Esc 一步取消,不进菜单
|
||||
if (S.marquee || S.lassoPts || (S.selection && S.selection.active)) { e.preventDefault(); clearMarquee(); return }
|
||||
if (S.penPath) { e.preventDefault(); S.penPath = null; renderObjects(); return }
|
||||
if (getPenEditingShape()) { e.preventDefault(); exitPenEdit(); return }
|
||||
if (S.selectedLayerId || S.selectedTextId || S.selectedShapeId || S.bitmapDrag || S.textDrag || S.shapeDrag) {
|
||||
@@ -1311,13 +1481,37 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
return
|
||||
}
|
||||
if (isTyping(e)) return
|
||||
|
||||
const mod = e.ctrlKey || e.metaKey
|
||||
const key = String(e.key || '').toLowerCase()
|
||||
// ---- 选区快捷键:与浮动条 / 右键菜单共用同一命令层 ----
|
||||
if (mod && key === 'a') { e.preventDefault(); runCommand('sel.all'); return }
|
||||
if (mod && e.shiftKey && key === 'i') { e.preventDefault(); runCommand('sel.invert'); return }
|
||||
if (mod && key === 'd') { e.preventDefault(); runCommand('sel.none'); return }
|
||||
if (mod && key === 'j') { e.preventDefault(); runCommand('sel.copy'); return }
|
||||
if (mod && key === 'x' && S.selection && S.selection.active) { e.preventDefault(); runCommand('sel.cut'); return }
|
||||
|
||||
// 数字键 1–0 保留兼容;另加 PS 习惯的字母键(无修饰键时才生效)
|
||||
const toolByKey = { '1': 'select', '2': 'brush', '3': 'eraser', '4': 'pen', '5': 'text', '6': 'rect', '7': 'circle', '8': 'arrow', '9': 'picker', '0': 'crop' }
|
||||
if (!e.ctrlKey && !e.metaKey && !e.altKey && Object.prototype.hasOwnProperty.call(toolByKey, e.key)) {
|
||||
const letterTools = { m: 'marquee', l: 'lasso', v: 'select', b: 'brush', e: 'eraser', t: 'text', c: 'crop' }
|
||||
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(toolByKey, e.key)) {
|
||||
e.preventDefault()
|
||||
setTool(toolByKey[e.key])
|
||||
return
|
||||
}
|
||||
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(letterTools, key)) {
|
||||
e.preventDefault()
|
||||
setTool(letterTools[key])
|
||||
return
|
||||
}
|
||||
|
||||
if (e.key === 'Delete' || e.key === 'Backspace') {
|
||||
// 有选区且没有选中矢量对象:只清当前层(用户裁定),不走「删对象」
|
||||
if (S.selection && S.selection.active && !S.selectedTextId && !S.selectedShapeId) {
|
||||
e.preventDefault()
|
||||
runCommand('sel.delete')
|
||||
return
|
||||
}
|
||||
if (S.selectedTextId) { e.preventDefault(); deleteSelectedText(); renderLayerPanel(); return }
|
||||
if (S.selectedShapeId) { e.preventDefault(); deleteSelectedShape(); renderLayerPanel(); return }
|
||||
}
|
||||
@@ -1326,13 +1520,13 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (!S.spaceDown) { S.spaceDown = true; updateCursor() }
|
||||
return
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === ']' || e.key === '[')) {
|
||||
if (mod && (e.key === ']' || e.key === '[')) {
|
||||
e.preventDefault()
|
||||
const up = e.key === ']'
|
||||
moveLayer(e.shiftKey ? (up ? 'top' : 'bottom') : (up ? 'up' : 'down'))
|
||||
return
|
||||
}
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'z') {
|
||||
if (mod && key === 'z') {
|
||||
e.preventDefault()
|
||||
if (e.shiftKey) redo(); else undo()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
/* export.js - 单张输出管道(P4,随 P1 一起带上)
|
||||
*
|
||||
* 一次只产出一个结果:覆盖节点 / 新建节点 / 下载。不做队列、不默认双输出。
|
||||
* 「电商 800×800 · ≤500KB」是可切换预设(用户 2026-11-04 裁定),
|
||||
* 预设 / 格式 / 背景存宿主 ctx.settings,下次打开沿用。
|
||||
*
|
||||
* 与宿主接口不变:glue.js 仍只收 (blob|dataURL, mode)。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { S, runtime } from './state.js'
|
||||
import { getCompositeCanvas } from './tools.js'
|
||||
import { toast } from './commands.js'
|
||||
|
||||
export const DEFAULT_EXPORT = Object.freeze({
|
||||
preset: 'original', // original | ecom800
|
||||
format: 'png', // png | jpeg | webp
|
||||
bg: 'transparent', // transparent | white
|
||||
maxKB: 0, // 0 = 不限
|
||||
size: 800 // 预设输出边长
|
||||
})
|
||||
|
||||
const SETTINGS_KEY = {
|
||||
preset: 'exportPreset', format: 'exportFormat', bg: 'exportBg',
|
||||
maxKB: 'exportMaxKB', size: 'exportSize'
|
||||
}
|
||||
|
||||
function settings() { return S.callbacks && S.callbacks.settings }
|
||||
|
||||
export function loadExportOptions() {
|
||||
const st = settings()
|
||||
const get = (k, d) => {
|
||||
let v = d
|
||||
if (st && typeof st.get === 'function') {
|
||||
try { const got = st.get(SETTINGS_KEY[k]); if (got !== undefined && got !== null) v = got } catch (e) { /* ignore */ }
|
||||
}
|
||||
return v
|
||||
}
|
||||
S.exportOptions = {
|
||||
preset: get('preset', DEFAULT_EXPORT.preset) === 'ecom800' ? 'ecom800' : 'original',
|
||||
format: ['png', 'jpeg', 'webp'].indexOf(get('format', DEFAULT_EXPORT.format)) >= 0 ? get('format', DEFAULT_EXPORT.format) : 'png',
|
||||
bg: get('bg', DEFAULT_EXPORT.bg) === 'white' ? 'white' : 'transparent',
|
||||
maxKB: Math.max(0, Number(get('maxKB', 0)) || 0),
|
||||
size: Math.max(64, Number(get('size', 800)) || 800)
|
||||
}
|
||||
if (S.exportOptions.preset === 'ecom800' && !S.exportOptions.maxKB) S.exportOptions.maxKB = 500
|
||||
renderExportUI()
|
||||
}
|
||||
|
||||
export function setExportOption(key, value) {
|
||||
if (!S.exportOptions) loadExportOptions()
|
||||
S.exportOptions[key] = value
|
||||
if (key === 'preset' && value === 'ecom800') S.exportOptions.maxKB = 500
|
||||
if (key === 'preset' && value === 'original') S.exportOptions.maxKB = 0
|
||||
const st = settings()
|
||||
if (st && typeof st.set === 'function') {
|
||||
try { st.set(SETTINGS_KEY[key], value) } catch (e) { /* ignore */ }
|
||||
}
|
||||
renderExportUI()
|
||||
}
|
||||
|
||||
/** 顶栏输出设置面板:按钮态 + 预设摘要 */
|
||||
export function renderExportUI() {
|
||||
const o = S.exportOptions || DEFAULT_EXPORT
|
||||
const root = runtime.el
|
||||
if (!root) return
|
||||
root.querySelectorAll('[data-export-key]').forEach(btn => {
|
||||
const on = String(o[btn.dataset.exportKey]) === String(btn.dataset.exportValue)
|
||||
btn.classList.toggle('active', on)
|
||||
btn.setAttribute('aria-pressed', String(on))
|
||||
})
|
||||
const summary = root.querySelector('.iwb-editor-export-summary')
|
||||
if (summary) summary.textContent = o.preset === 'ecom800'
|
||||
? (o.size + '×' + o.size + ' · ' + o.format.toUpperCase() + (o.maxKB ? ' · ≤' + o.maxKB + 'KB' : ''))
|
||||
: ('原尺寸 ' + S.imgW + '×' + S.imgH + ' · ' + o.format.toUpperCase())
|
||||
}
|
||||
|
||||
/** 事件委托:输出设置面板(下拉容器常驻 DOM,展开由 CSS class 控制) */
|
||||
export function bindExportUI() {
|
||||
const root = runtime.el
|
||||
if (!root) return
|
||||
const panel = root.querySelector('.iwb-editor-export-settings')
|
||||
const toggle = root.querySelector('[data-action="toggleExportSettings"]')
|
||||
if (panel && panel.dataset.bound === '1') return
|
||||
if (panel) panel.dataset.bound = '1'
|
||||
if (toggle && panel) {
|
||||
toggle.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
toggle.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const open = panel.classList.toggle('open')
|
||||
toggle.setAttribute('aria-expanded', String(open))
|
||||
})
|
||||
}
|
||||
if (panel) {
|
||||
panel.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
panel.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('[data-export-key]')
|
||||
if (!btn) return
|
||||
e.stopPropagation()
|
||||
let v = btn.dataset.exportValue
|
||||
if (btn.dataset.exportKey === 'maxKB' || btn.dataset.exportKey === 'size') v = Number(v)
|
||||
setExportOption(btn.dataset.exportKey, v)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 合成 → 尺寸/背景处理。返回结果画布(调用方负责释放) */
|
||||
export function buildOutputCanvas() {
|
||||
const o = S.exportOptions || DEFAULT_EXPORT
|
||||
const src = getCompositeCanvas()
|
||||
let out = src
|
||||
if (o.preset === 'ecom800') {
|
||||
const size = o.size
|
||||
const c = document.createElement('canvas')
|
||||
c.width = size
|
||||
c.height = size
|
||||
const cx = c.getContext('2d')
|
||||
if (o.bg === 'white' || o.format === 'jpeg') { cx.fillStyle = '#ffffff'; cx.fillRect(0, 0, size, size) }
|
||||
const long = Math.max(S.imgW, S.imgH) || 1
|
||||
const k = (size * 0.8) / long // 商品长边占比 80%(640px / 800px)
|
||||
const w = S.imgW * k, h = S.imgH * k
|
||||
cx.drawImage(src, (size - w) / 2, (size - h) / 2, w, h)
|
||||
src.width = 0; src.height = 0
|
||||
out = c
|
||||
} else if (o.bg === 'white' || o.format === 'jpeg') {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = S.imgW
|
||||
c.height = S.imgH
|
||||
const cx = c.getContext('2d')
|
||||
cx.fillStyle = '#ffffff'
|
||||
cx.fillRect(0, 0, c.width, c.height)
|
||||
cx.drawImage(src, 0, 0)
|
||||
src.width = 0; src.height = 0
|
||||
out = c
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function toBlob(canvas, mime, quality) {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
if (typeof canvas.toBlob !== 'function') { reject(new Error('当前环境不支持 toBlob')); return }
|
||||
canvas.toBlob((blob) => {
|
||||
if (blob) resolve(blob)
|
||||
else {
|
||||
try { resolve(dataUrlToBlob(canvas.toDataURL(mime, quality))) }
|
||||
catch (e) { reject(e) }
|
||||
}
|
||||
}, mime, quality)
|
||||
} catch (e) { reject(e) }
|
||||
})
|
||||
}
|
||||
|
||||
function dataUrlToBlob(dataUrl) {
|
||||
const comma = dataUrl.indexOf(',')
|
||||
const meta = dataUrl.slice(0, comma)
|
||||
const bin = atob(dataUrl.slice(comma + 1))
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
return new Blob([bytes], { type: (/^data:([^;,]+)/.exec(meta) || [])[1] || 'image/png' })
|
||||
}
|
||||
|
||||
/** 编码并按 ≤maxKB 迭代降质(jpeg/webp);PNG 无质量参数,明确提示而不是静默失败 */
|
||||
export async function encodeOutput(canvas) {
|
||||
const o = S.exportOptions || DEFAULT_EXPORT
|
||||
const mime = o.format === 'jpeg' ? 'image/jpeg' : o.format === 'webp' ? 'image/webp' : 'image/png'
|
||||
const limit = o.maxKB > 0 ? o.maxKB * 1024 : 0
|
||||
let blob = await toBlob(canvas, mime, 0.92)
|
||||
if (limit && blob.size > limit) {
|
||||
if (o.format === 'png') {
|
||||
toast('PNG 无法降质:当前 ' + Math.round(blob.size / 1024) + 'KB,可切换 JPG/WebP 或缩小尺寸', 'warn')
|
||||
} else {
|
||||
let q = 0.82
|
||||
for (let i = 0; i < 8 && blob.size > limit && q >= 0.3; i++) {
|
||||
blob = await toBlob(canvas, mime, q)
|
||||
q -= 0.09
|
||||
}
|
||||
if (blob.size > limit) toast('已尽力压缩,仍为 ' + Math.round(blob.size / 1024) + 'KB(目标 ≤' + o.maxKB + 'KB)', 'warn')
|
||||
}
|
||||
}
|
||||
return blob
|
||||
}
|
||||
|
||||
/** 发布前准备:返回 Blob + 体积信息,不碰宿主、不关闭编辑器 */
|
||||
export async function prepareOutput() {
|
||||
const canvas = buildOutputCanvas()
|
||||
try {
|
||||
const blob = await encodeOutput(canvas)
|
||||
const info = { bytes: blob.size, width: canvas.width, height: canvas.height, format: S.exportOptions.format, preset: S.exportOptions.preset }
|
||||
S.lastExport = info
|
||||
return { blob, info }
|
||||
} finally {
|
||||
canvas.width = 0
|
||||
canvas.height = 0
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载:一次一个文件,用完立即 revoke blob URL */
|
||||
export function downloadBlob(blob) {
|
||||
const o = S.exportOptions || DEFAULT_EXPORT
|
||||
const ext = o.format === 'jpeg' ? 'jpg' : o.format
|
||||
const raw = (S.callbacks && S.callbacks.imageName) || 'image.png'
|
||||
const name = String(raw).replace(/\.[^.]+$/, '') + '_edit.' + ext
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = name
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
if (a.parentNode) a.parentNode.removeChild(a)
|
||||
setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000)
|
||||
toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success')
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/* floating.js - 选区浮动操作条(便利版 UI 的核心)
|
||||
*
|
||||
* 它是纯视图:按钮只调用 commands.runCommand(),因此浮动条 / 右键菜单 / 快捷键
|
||||
* 三条入口天然一致;日后用户体验后决定保留、换位置或移除,都不影响选区功能。
|
||||
*
|
||||
* DOM 元素由 dom.js 静态生成(.iwb-editor-sel-bar),本模块只负责绑定、定位与显隐。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { S, runtime } from './state.js'
|
||||
import { runCommand, toast } from './commands.js'
|
||||
import { hasSelection, selectionInfo } from './selection.js'
|
||||
|
||||
let contextMode = false
|
||||
|
||||
function bar() {
|
||||
return runtime.el && runtime.el.querySelector('.iwb-editor-sel-bar')
|
||||
}
|
||||
|
||||
/** 事件委托:所有 [data-sel-cmd] 走同一命令层 */
|
||||
export function bindFloating() {
|
||||
const el = bar()
|
||||
if (!el || el.dataset.bound === '1') return
|
||||
el.dataset.bound = '1'
|
||||
el.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
el.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('[data-sel-cmd]')
|
||||
if (!btn) return
|
||||
e.stopPropagation()
|
||||
runCommand(btn.dataset.selCmd)
|
||||
contextMode = false
|
||||
positionFloating()
|
||||
})
|
||||
}
|
||||
|
||||
/** 图片坐标 → canvas-wrap 内屏幕坐标 */
|
||||
function imageToWrap(x, y) {
|
||||
const stack = S.canvasStack.getBoundingClientRect()
|
||||
const wrap = S.canvasWrap.getBoundingClientRect()
|
||||
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
|
||||
const pad = S.overlayPad || 0
|
||||
return {
|
||||
x: stack.left - wrap.left + (pad + x) * scale,
|
||||
y: stack.top - wrap.top + (pad + y) * scale
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定位:默认贴在选区右下角外侧;靠边时自动翻到左侧/上方,始终留在工作区内。
|
||||
* 蚂蚁线 rAF 每帧调用,因此缩放/平移时它会跟着选区走。
|
||||
*/
|
||||
export function positionFloating() {
|
||||
const el = bar()
|
||||
if (!el || !S.open) return
|
||||
const active = hasSelection()
|
||||
if (!active && !contextMode) { el.style.display = 'none'; return }
|
||||
el.style.display = 'flex'
|
||||
el.classList.toggle('as-menu', contextMode)
|
||||
|
||||
const wrapW = S.canvasWrap.clientWidth
|
||||
const wrapH = S.canvasWrap.clientHeight
|
||||
const bw = el.offsetWidth || 300
|
||||
const bh = el.offsetHeight || 36
|
||||
let left, top
|
||||
if (contextMode && el.dataset.cx !== undefined) {
|
||||
left = Number(el.dataset.cx)
|
||||
top = Number(el.dataset.cy)
|
||||
} else {
|
||||
const b = S.selection.bbox
|
||||
const p = imageToWrap(b.x + b.w, b.y + b.h)
|
||||
left = p.x + 10
|
||||
top = p.y + 8
|
||||
if (left + bw > wrapW - 8) left = imageToWrap(b.x, b.y).x + (b.w * (S.fitW * S.zoom) / S.imgW) - bw
|
||||
if (top + bh > wrapH - 8) top = imageToWrap(b.x, b.y).y - bh - 8
|
||||
}
|
||||
el.style.left = Math.max(8, Math.min(left, Math.max(8, wrapW - bw - 8))) + 'px'
|
||||
el.style.top = Math.max(8, Math.min(top, Math.max(8, wrapH - bh - 8))) + 'px'
|
||||
|
||||
// 无选区时禁用「需要选区」的按钮(右键菜单里仍能看到「全选」)
|
||||
el.querySelectorAll('[data-sel-cmd]').forEach(btn => {
|
||||
const need = btn.dataset.needsSel === '1'
|
||||
btn.disabled = need && !active
|
||||
})
|
||||
const info = el.querySelector('.iwb-editor-sel-info')
|
||||
if (info) {
|
||||
const s = selectionInfo()
|
||||
info.textContent = s ? (s.w + '×' + s.h + (s.feather ? ' · 羽化 ' + s.feather : '')) : '未框选'
|
||||
}
|
||||
}
|
||||
|
||||
/** 右键菜单:同一条操作条,定位到鼠标处 */
|
||||
export function showSelectionContext(e) {
|
||||
const el = bar()
|
||||
if (!el) return
|
||||
const wrap = S.canvasWrap.getBoundingClientRect()
|
||||
contextMode = true
|
||||
el.dataset.cx = String(e.clientX - wrap.left)
|
||||
el.dataset.cy = String(e.clientY - wrap.top)
|
||||
positionFloating()
|
||||
if (!hasSelection()) toast('右键菜单:可先「全选」,或框选后直接操作', 'info')
|
||||
}
|
||||
|
||||
export function hideSelectionContext() {
|
||||
if (!contextMode) return
|
||||
contextMode = false
|
||||
const el = bar()
|
||||
if (el) el.classList.remove('as-menu')
|
||||
positionFloating()
|
||||
}
|
||||
|
||||
export function isSelectionContextOpen() { return contextMode }
|
||||
@@ -1,35 +1,47 @@
|
||||
/* history.js - 历史快照与撤销/重做
|
||||
* 节:历史快照(所有位图图层 + 矢量对象)。
|
||||
* 约定:快照序列化依赖 shared/layer-logic.js 的 restorePath/needsPixelSnapshot,
|
||||
* 与 layers.js 各自独立实现「恢复图层」路径,互不 import。
|
||||
* 暴露 snapshotStats、HISTORY_MAX_ENTRIES、HISTORY_MAX_BYTES 供 __stats 观测。
|
||||
*
|
||||
* v1.1:快照升级为「完整图层集合」——除了像素,还记录图层的类型、名称、z、
|
||||
* image/sourceCanvas 引用等元数据。恢复时能删掉后来新增的层、重建被删掉的层,
|
||||
* 于是「复制/剪切到新层」「还原原图」这类会改变图层数量的操作也能 Ctrl+Z。
|
||||
* 快照只存在于会话内存里(ImageData / Image 引用都可以直接持有,不需要序列化)。
|
||||
*
|
||||
* 约定:快照端 needsPixelSnapshot() 与恢复端 restorePath() 共用 vendor/layer-logic.js,
|
||||
* 两边判定必须一致,否则会出现「没拍却要读」的像素丢失。
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
import { S } from './state.js'
|
||||
import { clearOverlay, updateCropInfo } from './crop.js'
|
||||
import { hideTextInput, renderObjects } from './objects.js'
|
||||
import { purgeVectorCanvases, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas } from './layers.js'
|
||||
import {
|
||||
createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer,
|
||||
renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles
|
||||
} from './layers.js'
|
||||
import { setupCanvas } from './viewport.js'
|
||||
import { updateAllUI } from './events.js'
|
||||
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
|
||||
|
||||
import { toast } from './commands.js'
|
||||
|
||||
// ============ 历史快照(所有位图图层 + 矢量对象) ============
|
||||
|
||||
// 快照开销统计:控制台 window.__iwbEditor.__stats() 可读
|
||||
export const snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 }
|
||||
|
||||
// restorePath()(快照端"要不要拍"与恢复端"要不要读"的共同判定)
|
||||
// 由 shared/layer-logic.js 提供,并有单元测试守护两边一致这条不变量。
|
||||
/**
|
||||
* 矢量对象上挂着运行时 DOM 画布(_canvas / _ctx)。JSON 深拷贝会把 canvas
|
||||
* 序列化成 {},撤销恢复后 reorderLayerCanvas() 就会拿 {} 去 insertBefore →
|
||||
* "parameter 1 is not of type 'Node'"。快照必须把这些运行时字段剔干净。
|
||||
*/
|
||||
function cloneVectors(arr) {
|
||||
return JSON.parse(JSON.stringify(arr || [], (key, value) => {
|
||||
if (key === '_canvas' || key === '_ctx') return undefined
|
||||
return value
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* 捕获当前状态
|
||||
* @param {{metaOnly?: boolean}} [opts]
|
||||
* metaOnly=true:只取几何/矢量/图层元数据。拖拽结束时仅用于"有没有变化"的比对,
|
||||
* 比对从不读像素,此前却照样做全量 getImageData —— 纯浪费。
|
||||
* 默认:只为 needsPixelSnapshot() 为 true 的图层拍像素,可重绘图层只存几何。
|
||||
* metaOnly=true:只取几何/矢量/图层元数据,用于拖拽结束时「有没有变化」的比对。
|
||||
*/
|
||||
export function snapshotState(opts) {
|
||||
const metaOnly = !!(opts && opts.metaOnly)
|
||||
@@ -43,42 +55,46 @@ import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/laye
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: layer.id,
|
||||
data,
|
||||
x: layer.x, y: layer.y, w: layer.w, h: layer.h,
|
||||
rotation: layer.rotation || 0,
|
||||
transformable: !!layer.transformable,
|
||||
locked: !!layer.locked
|
||||
}
|
||||
id: layer.id,
|
||||
data,
|
||||
// ---- 图层重建所需元数据(v1.1)----
|
||||
name: layer.name,
|
||||
z: layer.z,
|
||||
opacity: layer.opacity,
|
||||
visible: layer.visible,
|
||||
locked: !!layer.locked,
|
||||
transformable: !!layer.transformable,
|
||||
color: layer.color,
|
||||
lineWidth: layer.lineWidth,
|
||||
imageRef: layer.image || null,
|
||||
sourceRef: layer.sourceCanvas || null,
|
||||
sourceBox: layer._srcBox ? { ...layer._srcBox } : null,
|
||||
x: layer.x, y: layer.y, w: layer.w, h: layer.h,
|
||||
rotation: layer.rotation || 0
|
||||
}
|
||||
})
|
||||
snapshotStats.snapshots++
|
||||
return {
|
||||
imgW: S.imgW,
|
||||
imgH: S.imgH,
|
||||
activeLayerId: S.activeLayerId,
|
||||
bitmaps,
|
||||
texts: JSON.parse(JSON.stringify(S.textLayers)),
|
||||
shapes: JSON.parse(JSON.stringify(S.shapeLayers)),
|
||||
texts: cloneVectors(S.textLayers),
|
||||
shapes: cloneVectors(S.shapeLayers),
|
||||
layerOrder: S.layers.map(l => ({ id: l.id, name: l.name, z: l.z, opacity: l.opacity, visible: l.visible, locked: !!l.locked, x: l.x, y: l.y, w: l.w, h: l.h }))
|
||||
}
|
||||
}
|
||||
|
||||
// 历史既限条数也限字节:大图下"固定 50 条全量像素"峰值可超过 1GB
|
||||
export const HISTORY_MAX_ENTRIES = 50
|
||||
/** 字节预算上限/下限:预算随图幅自适应,见 historyBudgetBytes() */
|
||||
export const HISTORY_MAX_BYTES = 128 * 1024 * 1024
|
||||
const HISTORY_MIN_BYTES = 32 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* 快照字节预算(按图幅自适应):约「4 条全幅快照」,下限 32MB、上限 128MB。
|
||||
* 固定 128MB 的问题:1024 预览图每条仅 4MB ⇒ 可囤 32 条(纯浪费);
|
||||
* 而 4K 图每条 33MB ⇒ 天然只能放 3 条,与上限无关。按图幅算让
|
||||
* 小图少囤、大图保持现有撤销深度。
|
||||
*/
|
||||
export function historyBudgetBytes() {
|
||||
const px = (S.imgW || 0) * (S.imgH || 0) * 4
|
||||
if (!px) return HISTORY_MAX_BYTES
|
||||
return Math.min(HISTORY_MAX_BYTES, Math.max(HISTORY_MIN_BYTES, px * 4))
|
||||
}
|
||||
|
||||
/** 一条历史快照的大致内存占用(像素为主,矢量用序列化长度估算) */
|
||||
function stateBytes(state) {
|
||||
let n = 0
|
||||
if (state && state.bitmaps) {
|
||||
@@ -93,9 +109,9 @@ import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/laye
|
||||
return n
|
||||
}
|
||||
|
||||
/** 压入栈并执行"条数 + 字节"双预算,超出丢最旧 */
|
||||
export function pushHistory(stack, state) {
|
||||
export function pushHistory(stack, state, label) {
|
||||
state.__bytes = stateBytes(state)
|
||||
if (label) state.__label = label
|
||||
stack.push(state)
|
||||
const budget = historyBudgetBytes()
|
||||
let total = stack.reduce((sum, s) => sum + (s.__bytes || 0), 0)
|
||||
@@ -106,97 +122,209 @@ import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/laye
|
||||
}
|
||||
|
||||
/** 操作前调用:压入历史,清空重做栈 */
|
||||
export function saveSnapshot() {
|
||||
pushHistory(S.history, snapshotState())
|
||||
export function saveSnapshot(label) {
|
||||
pushHistory(S.history, snapshotState(), label)
|
||||
S.redoStack = []
|
||||
}
|
||||
|
||||
/** 恢复到指定状态 */
|
||||
/** 按快照元数据重建一个已被删除的位图图层 */
|
||||
function recreateLayer(bm) {
|
||||
const canvas = createLayerCanvas()
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||
return {
|
||||
id: bm.id,
|
||||
name: bm.name || ('图层 ' + bm.id),
|
||||
canvas,
|
||||
ctx,
|
||||
opacity: bm.opacity == null ? 1 : bm.opacity,
|
||||
visible: bm.visible !== false,
|
||||
locked: !!bm.locked,
|
||||
transformable: !!bm.transformable,
|
||||
color: bm.color,
|
||||
lineWidth: bm.lineWidth,
|
||||
image: bm.imageRef || null,
|
||||
sourceCanvas: bm.sourceRef || null,
|
||||
_srcBox: bm.sourceBox || null,
|
||||
x: bm.x, y: bm.y, w: bm.w, h: bm.h,
|
||||
rotation: bm.rotation || 0,
|
||||
z: bm.z || 0
|
||||
}
|
||||
}
|
||||
|
||||
function releaseLayer(layer) {
|
||||
try {
|
||||
if (layer.canvas && layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
|
||||
if (layer.canvas) { layer.canvas.width = 0; layer.canvas.height = 0 }
|
||||
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
|
||||
}
|
||||
|
||||
/** 恢复到指定状态(含图层增删) */
|
||||
function restoreState(state) {
|
||||
purgeVectorCanvases()
|
||||
for (const l of S.layers) l._bounds = undefined
|
||||
if (state.bitmaps) {
|
||||
for (let i = 0; i < state.bitmaps.length; i++) {
|
||||
const bm = state.bitmaps[i]
|
||||
const layer = S.layers.find(l => l.id === bm.id)
|
||||
|
||||
const snaps = state.bitmaps || []
|
||||
const want = new Set(snaps.map(b => b.id))
|
||||
// ① 删掉「快照里没有」的层(撤销复制/粘贴/选区新层)
|
||||
for (let i = S.layers.length - 1; i >= 0; i--) {
|
||||
if (!want.has(S.layers[i].id)) {
|
||||
releaseLayer(S.layers[i])
|
||||
S.layers.splice(i, 1)
|
||||
}
|
||||
}
|
||||
// ② 按快照顺序补齐/恢复
|
||||
const ordered = []
|
||||
for (const bm of snaps) {
|
||||
let layer = S.layers.find(l => l.id === bm.id)
|
||||
if (!layer) {
|
||||
layer = recreateLayer(bm)
|
||||
S.layers.push(layer)
|
||||
if (bm.data) {
|
||||
try { layer.ctx.putImageData(bm.data, 0, 0) } catch (e) { /* ignore */ }
|
||||
} else if (restorePath(layer) === 'redraw') {
|
||||
redrawBitmapLayer(layer)
|
||||
}
|
||||
} else {
|
||||
layer.x = bm.x
|
||||
layer.y = bm.y
|
||||
layer.w = bm.w
|
||||
layer.h = bm.h
|
||||
layer.locked = !!bm.locked
|
||||
layer.rotation = bm.rotation || 0
|
||||
if (isDrawableLayer(layer)) {
|
||||
layer._srcBox = null
|
||||
layer.sourceCanvas = null
|
||||
layer.rotation = 0
|
||||
layer.x = 0
|
||||
layer.y = 0
|
||||
layer.w = S.imgW
|
||||
layer.h = S.imgH
|
||||
layer._bounds = undefined
|
||||
}
|
||||
if (restorePath(layer) === 'redraw') {
|
||||
redrawBitmapLayer(layer)
|
||||
} else if (bm.data) {
|
||||
try {
|
||||
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
|
||||
layer.ctx.putImageData(bm.data, 0, 0)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
ordered.push(layer)
|
||||
}
|
||||
S.layers = ordered
|
||||
|
||||
if (state.layerOrder) {
|
||||
for (const meta of state.layerOrder) {
|
||||
const layer = S.layers.find(l => l.id === meta.id)
|
||||
if (layer) {
|
||||
layer.x = bm.x
|
||||
layer.y = bm.y
|
||||
layer.w = bm.w
|
||||
layer.h = bm.h
|
||||
layer.locked = !!bm.locked
|
||||
layer.rotation = bm.rotation || 0
|
||||
if (isDrawableLayer(layer)) {
|
||||
layer._srcBox = null
|
||||
layer.sourceCanvas = null
|
||||
layer.rotation = 0
|
||||
layer.x = 0
|
||||
layer.y = 0
|
||||
layer.w = S.imgW
|
||||
layer.h = S.imgH
|
||||
layer._bounds = undefined
|
||||
}
|
||||
// 快照端用 restorePath() 决定是否拍像素,这里用同一判定决定是否读像素
|
||||
if (restorePath(layer) === 'redraw') {
|
||||
redrawBitmapLayer(layer)
|
||||
} else if (bm.data) {
|
||||
try {
|
||||
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
|
||||
layer.ctx.putImageData(bm.data, 0, 0)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
layer.name = meta.name
|
||||
layer.z = meta.z
|
||||
layer.opacity = meta.opacity == null ? 1 : meta.opacity
|
||||
layer.visible = meta.visible !== false
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.layerOrder) {
|
||||
for (const meta of state.layerOrder) {
|
||||
const layer = S.layers.find(l => l.id === meta.id)
|
||||
if (layer) { layer.name = meta.name; layer.z = meta.z; layer.opacity = meta.opacity == null ? 1 : meta.opacity; layer.visible = meta.visible !== false; layer.locked = !!meta.locked }
|
||||
}
|
||||
reorderLayerCanvas()
|
||||
}
|
||||
S.textLayers = state.texts ? JSON.parse(JSON.stringify(state.texts)) : []
|
||||
S.shapeLayers = state.shapes ? JSON.parse(JSON.stringify(state.shapes)) : []
|
||||
if (!S.layers.some(l => l.id === S.activeLayerId)) S.activeLayerId = S.layers.length ? S.layers[S.layers.length - 1].id : null
|
||||
if (state.activeLayerId && S.layers.some(l => l.id === state.activeLayerId)) S.activeLayerId = state.activeLayerId
|
||||
S.zCounter = Math.max(S.zCounter, ...S.layers.map(l => l.z || 0), ...(state.texts || []).map(t => t.z || 0), ...(state.shapes || []).map(s => s.z || 0))
|
||||
|
||||
S.textLayers = cloneVectors(state.texts)
|
||||
S.shapeLayers = cloneVectors(state.shapes)
|
||||
S.selectedTextId = null
|
||||
S.textDrag = null
|
||||
S.selectedShapeId = null
|
||||
S.shapeDrag = null
|
||||
S.selectedLayerId = null
|
||||
S.bitmapDrag = null
|
||||
S.penPath = null
|
||||
S.penEditId = null
|
||||
// 撤销不动选区:选区是「视图状态」,不是像素状态,避免 Ctrl+Z 后框消失还要重画
|
||||
reorderLayerCanvas()
|
||||
updateLayerCanvasStyles()
|
||||
renderObjects()
|
||||
renderLayerPanel()
|
||||
updateCropInfo()
|
||||
}
|
||||
|
||||
export function undo() {
|
||||
if (S.placingImage) return
|
||||
// bitmapDrag 与 textDrag/shapeDrag 对称:位图层拖拽进行中不允许撤销
|
||||
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
|
||||
if (S.history.length === 0) return
|
||||
if (S.history.length === 0) { toast('没有可撤销的操作'); return }
|
||||
pushHistory(S.redoStack, snapshotState())
|
||||
restoreState(S.history.pop())
|
||||
if (S.renderAll) S.renderAll()
|
||||
}
|
||||
|
||||
export function redo() {
|
||||
if (S.placingImage) return
|
||||
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
|
||||
if (S.redoStack.length === 0) return
|
||||
if (S.redoStack.length === 0) { toast('没有可重做的操作'); return }
|
||||
pushHistory(S.history, snapshotState())
|
||||
restoreState(S.redoStack.pop())
|
||||
if (S.renderAll) S.renderAll()
|
||||
}
|
||||
|
||||
export function resetDraw() {
|
||||
purgeVectorCanvases()
|
||||
// 清空所有位图图层(保留原图层的内容不变,只清画笔层和后续图层)
|
||||
for (const layer of S.layers) {
|
||||
if (layer.id !== 'base') {
|
||||
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
|
||||
if (layer.sourceCanvas) layer.sourceCanvas.getContext('2d').clearRect(0, 0, layer.sourceCanvas.width, layer.sourceCanvas.height)
|
||||
}
|
||||
/**
|
||||
* 还原原图(用户 2026-11-04 裁定):清空标注 = 全部还原到刚打开时的状态 ——
|
||||
* 删掉所有非原图图层、清掉所有绘制/矢量、复位变换与选区,只留「原图 + 空画笔层」。
|
||||
* 整步记一个快照,Ctrl+Z 可完整恢复(包括被删的粘贴层与图形)。
|
||||
* 旧版 resetDraw() 只清像素、留下空白层且清空撤销栈,已废弃。
|
||||
*/
|
||||
export function restoreAll() {
|
||||
if (!S.originalImage) return
|
||||
const img = S.originalImage
|
||||
const ow = img.naturalWidth || img.width
|
||||
const oh = img.naturalHeight || img.height
|
||||
const sizeChanged = ow !== S.imgW || oh !== S.imgH
|
||||
|
||||
// 裁剪会改变画布尺寸且(P2 之前)会清空历史,此路径无法用像素快照回退;
|
||||
// 明确 toast 告知,不做「假的可撤销」。
|
||||
if (sizeChanged) {
|
||||
S.imgW = ow
|
||||
S.imgH = oh
|
||||
S.zoom = 1
|
||||
setupCanvas(img)
|
||||
S.history = []
|
||||
S.redoStack = []
|
||||
clearAllEditState()
|
||||
updateAllUI()
|
||||
toast('已还原为原图(裁剪后的画布尺寸已复位)', 'success')
|
||||
return
|
||||
}
|
||||
S.history = []
|
||||
S.redoStack = []
|
||||
S.cropRect = null
|
||||
S.cropHandle = null
|
||||
S.cropMoving = false
|
||||
S.moveStart = null
|
||||
|
||||
saveSnapshot('还原原图')
|
||||
const base = S.layers.find(l => l.id === 'base')
|
||||
for (const layer of S.layers) {
|
||||
if (layer !== base) releaseLayer(layer)
|
||||
}
|
||||
if (base) {
|
||||
base.ctx.clearRect(0, 0, S.imgW, S.imgH)
|
||||
base.ctx.drawImage(img, 0, 0)
|
||||
base.locked = true
|
||||
base.visible = true
|
||||
base.opacity = 1
|
||||
base.z = 0
|
||||
}
|
||||
const drawCanvas = createLayerCanvas()
|
||||
const drawCtx = drawCanvas.getContext('2d', { willReadFrequently: true })
|
||||
const draw = {
|
||||
id: 'draw', name: '画笔标注', canvas: drawCanvas, ctx: drawCtx,
|
||||
opacity: 1, visible: true, locked: false, transformable: true,
|
||||
x: 0, y: 0, w: S.imgW, h: S.imgH, rotation: 0,
|
||||
color: S.color, lineWidth: S.brushSize, z: 1
|
||||
}
|
||||
S.layers = base ? [base, draw] : [draw]
|
||||
S.activeLayerId = 'draw'
|
||||
S.zCounter = 1
|
||||
clearAllEditState()
|
||||
if (S.renderAll) S.renderAll()
|
||||
renderLayerPanel()
|
||||
hideTextInput()
|
||||
toast('已还原为原图,Ctrl+Z 可撤销', 'success')
|
||||
}
|
||||
|
||||
function clearAllEditState() {
|
||||
S.textLayers = []
|
||||
S.selectedTextId = null
|
||||
S.textDrag = null
|
||||
@@ -206,21 +334,23 @@ import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/laye
|
||||
S.shapeDrag = null
|
||||
S.selectedLayerId = null
|
||||
S.bitmapDrag = null
|
||||
renderObjects()
|
||||
renderLayerPanel()
|
||||
S.penPath = null
|
||||
S.penEditId = null
|
||||
S.cropRect = null
|
||||
S.cropHandle = null
|
||||
S.cropMoving = false
|
||||
S.moveStart = null
|
||||
S.selection = null
|
||||
S.marquee = null
|
||||
S.lassoPts = null
|
||||
S.pickerComposite = null
|
||||
clearOverlay()
|
||||
updateCropInfo()
|
||||
hideTextInput()
|
||||
reorderLayerCanvas()
|
||||
updateLayerCanvasStyles()
|
||||
renderObjects()
|
||||
}
|
||||
|
||||
/** 复原:一键回到打开编辑器时的原始图片(撤销所有标注与裁剪) */
|
||||
export function restoreOriginal() {
|
||||
if (!S.originalImage) return
|
||||
if (!window.confirm('复原将丢弃所有标注和裁剪,回到原始图片。确定继续吗?')) return
|
||||
S.imgW = S.originalImage.naturalWidth || S.originalImage.width
|
||||
S.imgH = S.originalImage.naturalHeight || S.originalImage.height
|
||||
S.zoom = 1
|
||||
setupCanvas(S.originalImage)
|
||||
resetDraw()
|
||||
updateAllUI()
|
||||
}
|
||||
/** 兼容旧入口:清空标注按钮 / 更多菜单都指向 restoreAll */
|
||||
export function resetDraw() { restoreAll() }
|
||||
export function restoreOriginal() { restoreAll() }
|
||||
@@ -28,18 +28,24 @@
|
||||
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 } from './layers.js'
|
||||
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
|
||||
import { createEl, loadImage } from './dom.js'
|
||||
import { getCompositeCanvas } from './tools.js'
|
||||
import { hideTextInput } from './objects.js'
|
||||
import { renderObjects, hideTextInput } from './objects.js'
|
||||
import { setupCanvas } from './viewport.js'
|
||||
import { updateAllUI } from './events.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)
|
||||
@@ -52,6 +58,13 @@ import { updateAllUI } from './events.js'
|
||||
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'
|
||||
@@ -104,6 +117,44 @@ import { updateAllUI } from './events.js'
|
||||
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)
|
||||
}
|
||||
|
||||
export function close() {
|
||||
@@ -120,6 +171,8 @@ import { updateAllUI } from './events.js'
|
||||
S.penPath = null
|
||||
S.textEditingId = null
|
||||
clearSelection()
|
||||
hideSelectionContext()
|
||||
disposeSelection()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,7 +211,7 @@ import { updateAllUI } from './events.js'
|
||||
}
|
||||
S.layers = []
|
||||
// 5) 工作 canvas:text / stroke / overlay(overlay 含 18% 交互边距,4K 图约 74MB)
|
||||
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas]) {
|
||||
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) 矢量对象的画布缓存
|
||||
@@ -171,40 +224,21 @@ import { updateAllUI } from './events.js'
|
||||
* 用 toBlob 而非 toDataURL —— 编码结果落在浏览器 Blob 存储(堆外),
|
||||
* 省掉全幅 base64 字符串(4K 图约 44MB JS 堆驻留);onResult 收到 Blob 或 dataURL 均可。
|
||||
*/
|
||||
export function exportResult(mode) {
|
||||
/**
|
||||
* 单张输出:prepareOutput() 负责合成 → 尺寸/背景 → 编码(含 ≤500KB 降质)。
|
||||
* 一次只产出一个结果;download 只下载、不关编辑器、不回写宿主节点。
|
||||
*/
|
||||
export async function exportResult(mode) {
|
||||
if (S.placingImage) cancelImagePlacement()
|
||||
const tmp = getCompositeCanvas()
|
||||
let done = false
|
||||
const finish = (out) => {
|
||||
if (done) return
|
||||
done = true
|
||||
tmp.width = 0 // 合成画布用完即弃(33MB@4K)
|
||||
tmp.height = 0
|
||||
if (S.callbacks && S.callbacks.onResult) {
|
||||
S.callbacks.onResult(out, mode)
|
||||
}
|
||||
close()
|
||||
}
|
||||
const fail = (e) => {
|
||||
if (done) return
|
||||
done = true
|
||||
tmp.width = 0
|
||||
tmp.height = 0
|
||||
console.error('[IWB编辑器] 导出失败:', e)
|
||||
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('图片跨域无法导出')
|
||||
}
|
||||
try {
|
||||
if (typeof tmp.toBlob === 'function') {
|
||||
tmp.toBlob((blob) => {
|
||||
if (blob) { finish(blob); return }
|
||||
// toBlob 对非 origin-clean 画布返回 null → 退回 toDataURL 让它抛出明确的 SecurityError
|
||||
try { finish(tmp.toDataURL('image/png')) } catch (e) { fail(e) }
|
||||
}, 'image/png')
|
||||
return
|
||||
}
|
||||
finish(tmp.toDataURL('image/png'))
|
||||
const { blob } = await prepareOutput()
|
||||
if (mode === 'download') { downloadBlob(blob); return }
|
||||
if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode)
|
||||
close()
|
||||
} catch (e) {
|
||||
fail(e)
|
||||
console.error('[IWB编辑器] 导出失败:', e)
|
||||
toast('导出失败:' + ((e && e.message) || '图片可能跨域'), 'error')
|
||||
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('导出失败:' + ((e && e.message) || '图片跨域'))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,8 +261,31 @@ import { updateAllUI } from './events.js'
|
||||
...snapshotStats
|
||||
})
|
||||
|
||||
/** 开发/回归观测口:本地探针与真站 e2e 用它断言图层、选区与像素,不参与业务逻辑 */
|
||||
const __debug = () => ({
|
||||
open: S.open,
|
||||
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 })),
|
||||
activeLayerId: S.activeLayerId,
|
||||
selection: selectionInfo(),
|
||||
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,
|
||||
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 }
|
||||
}
|
||||
})
|
||||
|
||||
window.__iwbEditor = {
|
||||
open,
|
||||
close,
|
||||
__stats
|
||||
__stats,
|
||||
__debug
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelecte
|
||||
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
|
||||
import { drawShape } from './tools.js'
|
||||
import { saveSnapshot, snapshotState } from './history.js'
|
||||
import { startImagePlacement } from './placement.js'
|
||||
import { placeImageDirectly } from './placement.js'
|
||||
import { updateBrushParamUI, updateColorUI } from './events.js'
|
||||
import { isDrawableLayer } from '../vendor/layer-logic.js'
|
||||
|
||||
@@ -41,7 +41,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
|
||||
// 与合成/导出/面板/命中测试共用同一份 z 序,杜绝「面板顺序 ≠ 实际叠放」
|
||||
for (const u of layerUnits()) {
|
||||
const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas
|
||||
if (!el) continue
|
||||
// 快照恢复后的矢量对象可能带着被 JSON 序列化过的伪画布({}),必须挡住
|
||||
if (!el || el.nodeType !== 1) continue
|
||||
S.canvasStack.insertBefore(el, S.strokeCanvas)
|
||||
el.style.display = u.obj.visible === false ? 'none' : 'block'
|
||||
}
|
||||
@@ -312,9 +313,10 @@ export function setActiveLayer(id) {
|
||||
renderObjects()
|
||||
}
|
||||
|
||||
/** 添加位图图层(导入图片) — 启动放置流程,先调整大小/位置再确认 */
|
||||
/** 添加位图图层(导入图片)— 便利版:一步落层,不再需要 Enter 二次确认
|
||||
* 需要调大小/位置时切换到「选择」工具拖动 8 个手柄;Ctrl+Z 可撤销这一步。 */
|
||||
export function addBitmapLayer(img) {
|
||||
startImagePlacement(img)
|
||||
placeImageDirectly(img)
|
||||
}
|
||||
|
||||
/** 新建空白图层 */
|
||||
@@ -366,7 +368,7 @@ export function setActiveLayer(id) {
|
||||
|
||||
// ============ 矢量对象独立画布(位图/矢量统一排序) ============
|
||||
function vecCanvasFor(obj) {
|
||||
if (!obj._canvas || !obj._canvas.parentNode) {
|
||||
if (!obj._canvas || obj._canvas.nodeType !== 1 || !obj._canvas.parentNode) {
|
||||
const c = document.createElement('canvas')
|
||||
c.className = 'iwb-editor-vec-canvas'
|
||||
c.width = S.imgW
|
||||
@@ -390,7 +392,7 @@ export function setActiveLayer(id) {
|
||||
return obj
|
||||
}
|
||||
export function removeVecCanvas(obj) {
|
||||
if (obj && obj._canvas) {
|
||||
if (obj && obj._canvas && obj._canvas.nodeType === 1) {
|
||||
if (obj._canvas.parentNode) obj._canvas.parentNode.removeChild(obj._canvas)
|
||||
obj._canvas = null
|
||||
obj._ctx = null
|
||||
|
||||
@@ -38,28 +38,20 @@ import { updateCursor } from './events.js'
|
||||
drawPlacementPreview()
|
||||
}
|
||||
|
||||
/** 确认图片放置:创建新位图图层并绘制图片 */
|
||||
export function confirmImagePlacement() {
|
||||
if (!S.placingImage) return
|
||||
const { img, x, y, w, h } = S.placingImage
|
||||
const placementRotation = S.placingImage.rotation || 0
|
||||
S.placingImage = null
|
||||
S.placingHandle = null
|
||||
S.placingStart = null
|
||||
clearOverlay()
|
||||
// 创建图层
|
||||
/** 图片参数 → 新位图图层(放置确认与「直接落层」共用) */
|
||||
function commitImageAsLayer(img, x, y, w, h, rotation) {
|
||||
const id = 'L' + Date.now() + Math.floor(Math.random() * 1000)
|
||||
const canvas = createLayerCanvas()
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||
ctx.clearRect(0, 0, S.imgW, S.imgH)
|
||||
const layer = {
|
||||
id,
|
||||
name: '图层 ' + (S.layers.length + 1), image: img, x, y, w, h, rotation: placementRotation, transformable: true,
|
||||
name: '图层 ' + (S.layers.length + 1), image: img, x, y, w, h, rotation: rotation || 0, transformable: true,
|
||||
canvas,
|
||||
ctx,
|
||||
opacity: 1,
|
||||
visible: true,
|
||||
locked: false,
|
||||
locked: false,
|
||||
// 与矢量对象 / 空白图层共用同一个 z 计数器(旧值 S.layers.length 会和 ++S.zCounter 撞车,
|
||||
// 导致粘贴的截图与图形 z 相同:排序按钮交换 z 无效、命中测试选错对象)
|
||||
z: ++S.zCounter
|
||||
@@ -71,9 +63,41 @@ import { updateCursor } from './events.js'
|
||||
setActiveLayer(id)
|
||||
updateLayerCanvasStyles()
|
||||
renderLayerPanel()
|
||||
return layer
|
||||
}
|
||||
|
||||
/** 确认图片放置:创建新位图图层并绘制图片 */
|
||||
export function confirmImagePlacement() {
|
||||
if (!S.placingImage) return
|
||||
const { img, x, y, w, h } = S.placingImage
|
||||
const placementRotation = S.placingImage.rotation || 0
|
||||
S.placingImage = null
|
||||
S.placingHandle = null
|
||||
S.placingStart = null
|
||||
clearOverlay()
|
||||
commitImageAsLayer(img, x, y, w, h, placementRotation)
|
||||
updateCursor()
|
||||
}
|
||||
|
||||
/**
|
||||
* 便利版:粘贴 / 导入图片一步落层,不再要求 Enter 二次确认。
|
||||
* 默认原大但不超过画布 50%、居中;要调整大小/位置直接切选择工具拖手柄。
|
||||
* 整步有快照,Ctrl+Z 可撤销,Esc 也能当作「后悔」的兜底。
|
||||
*/
|
||||
export function placeImageDirectly(img) {
|
||||
const iw = img.naturalWidth || img.width
|
||||
const ih = img.naturalHeight || img.height
|
||||
const ratio = Math.min((S.imgW * 0.5) / iw, (S.imgH * 0.5) / ih, 1)
|
||||
const w = Math.max(10, Math.round(iw * ratio))
|
||||
const h = Math.max(10, Math.round(ih * ratio))
|
||||
const layer = commitImageAsLayer(img, Math.round((S.imgW - w) / 2), Math.round((S.imgH - h) / 2), w, h, 0)
|
||||
// 粘贴常发生在刚点过工具按钮之后;若焦点还停在按钮上,用户习惯性补按 Enter
|
||||
// 会激活那个按钮(最坏情况是「还原原图」)。落层后主动把焦点还给画布。
|
||||
try { if (document.activeElement && document.activeElement.blur) document.activeElement.blur() } catch (e) { /* ignore */ }
|
||||
if (S.renderAll) S.renderAll()
|
||||
return layer
|
||||
}
|
||||
|
||||
/** 取消图片放置 */
|
||||
export function cancelImagePlacement() {
|
||||
S.placingImage = null
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
/* selection.js - 选区模型、蚂蚁线与像素命令(P1)
|
||||
*
|
||||
* 唯一真源:S.selection = { path, outlinePath, bbox, fillRule, feather, kind, inverted }
|
||||
* path 图片坐标系的 Path2D,清除 / 复制 / 剪切 / 填充 / 限制画笔全部复用它
|
||||
* outlinePath 只用于画蚂蚁线(反选时不应把整图外框也画成虚线)
|
||||
* fillRule 'nonzero' | 'evenodd'(反选 = 整图矩形 + 原 path,evenodd 填充)
|
||||
*
|
||||
* 蚂蚁线画在独立的 selectionCanvas 上:renderObjects() 里那句 clearOverlay()
|
||||
* 只清交互层,不会把选区擦掉,也不会反过来擦掉裁剪框/选中手柄。
|
||||
* 掩膜只覆盖 bbox(+ 羽化边距),不做全幅 getImageData —— 4K 图下这是内存底线。
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
import { S } from './state.js'
|
||||
import { clamp, getPos } from './viewport.js'
|
||||
import { clearOverlay } from './crop.js'
|
||||
import { defineCommand, runCommand, toast } from './commands.js'
|
||||
import { createLayerCanvas, getActiveLayer, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
|
||||
|
||||
// ============ 状态查询 ============
|
||||
export function hasSelection() { return !!(S.selection && S.selection.active) }
|
||||
|
||||
/** 供状态栏 / 浮动条显示 */
|
||||
export function selectionInfo() {
|
||||
if (!hasSelection()) return null
|
||||
const b = S.selection.bbox
|
||||
return { kind: S.selection.kind, x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h), feather: S.selection.feather || 0 }
|
||||
}
|
||||
|
||||
// ============ 选区图层(独立 canvas) ============
|
||||
/** 清 selectionCanvas(与 crop.js#clearOverlay 同一坐标基准,但互不干扰) */
|
||||
function clearSelectionCanvas() {
|
||||
const ctx = S.selectionCtx
|
||||
if (!ctx) return
|
||||
const pad = S.overlayPad || 0
|
||||
ctx.save()
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
|
||||
ctx.restore()
|
||||
ctx.setTransform(1, 0, 0, 1, pad, pad)
|
||||
}
|
||||
|
||||
export function clearCursorCanvas() {
|
||||
const ctx = S.cursorCtx
|
||||
if (!ctx) return
|
||||
const pad = S.overlayPad || 0
|
||||
ctx.save()
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
|
||||
ctx.restore()
|
||||
ctx.setTransform(1, 0, 0, 1, pad, pad)
|
||||
}
|
||||
|
||||
/** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */
|
||||
export function renderSelection() {
|
||||
if (!S.selectionCtx) return
|
||||
clearSelectionCanvas()
|
||||
const ctx = S.selectionCtx
|
||||
const k = 1 / Math.max(S.zoom, 0.0001)
|
||||
|
||||
// 拉框 / 套索过程中:画预览,不画正式选区
|
||||
if (S.marquee || (S.lassoPts && S.lassoPts.length > 1)) {
|
||||
ctx.save()
|
||||
ctx.lineWidth = 1.5 * k
|
||||
ctx.strokeStyle = '#ffffff'
|
||||
ctx.setLineDash([5 * k, 4 * k])
|
||||
if (S.marquee) {
|
||||
const b = marqueeBox()
|
||||
if (S.selectionKind === 'ellipse') {
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(1, b.w / 2), Math.max(1, b.h / 2), 0, 0, Math.PI * 2)
|
||||
ctx.stroke()
|
||||
} else ctx.strokeRect(b.x, b.y, b.w, b.h)
|
||||
} else {
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(S.lassoPts[0].x, S.lassoPts[0].y)
|
||||
for (let i = 1; i < S.lassoPts.length; i++) ctx.lineTo(S.lassoPts[i].x, S.lassoPts[i].y)
|
||||
ctx.closePath()
|
||||
ctx.stroke()
|
||||
}
|
||||
ctx.restore()
|
||||
return
|
||||
}
|
||||
if (!hasSelection()) return
|
||||
const p = S.selection.outlinePath || S.selection.path
|
||||
ctx.save()
|
||||
ctx.lineWidth = 1.4 * k
|
||||
ctx.setLineDash([5 * k, 5 * k])
|
||||
ctx.lineDashOffset = (S._antOffset || 0) * k
|
||||
ctx.strokeStyle = 'rgba(0,0,0,0.85)'
|
||||
ctx.stroke(p)
|
||||
ctx.lineDashOffset = ((S._antOffset || 0) + 5) * k
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.95)'
|
||||
ctx.stroke(p)
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
/** 启动/停止蚂蚁线动画;同时每帧刷新浮动条位置(缩放/平移时跟着选区走) */
|
||||
export function syncAnts() {
|
||||
if (hasSelection() && S.open) {
|
||||
if (!S._antFrame) {
|
||||
const tick = () => {
|
||||
S._antOffset = ((S._antOffset || 0) + 0.55) % 10
|
||||
renderSelection()
|
||||
if (S.positionFloating) S.positionFloating()
|
||||
S._antFrame = requestAnimationFrame(tick)
|
||||
}
|
||||
S._antFrame = requestAnimationFrame(tick)
|
||||
}
|
||||
} else if (S._antFrame) {
|
||||
cancelAnimationFrame(S._antFrame)
|
||||
S._antFrame = 0
|
||||
}
|
||||
}
|
||||
|
||||
// ============ 建立选区 ============
|
||||
function rectFromPoints(x0, y0, x1, y1) {
|
||||
const x = Math.min(x0, x1), y = Math.min(y0, y1)
|
||||
return { x, y, w: Math.abs(x1 - x0), h: Math.abs(y1 - y0) }
|
||||
}
|
||||
|
||||
function pathForBox(b, kind) {
|
||||
const p = new Path2D()
|
||||
if (kind === 'ellipse') {
|
||||
p.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(0.5, b.w / 2), Math.max(0.5, b.h / 2), 0, 0, Math.PI * 2)
|
||||
} else p.rect(b.x, b.y, Math.max(0.5, b.w), Math.max(0.5, b.h))
|
||||
return p
|
||||
}
|
||||
|
||||
function pathForLasso(pts) {
|
||||
const p = new Path2D()
|
||||
if (!pts.length) return p
|
||||
p.moveTo(pts[0].x, pts[0].y)
|
||||
for (let i = 1; i < pts.length; i++) p.lineTo(pts[i].x, pts[i].y)
|
||||
p.closePath()
|
||||
return p
|
||||
}
|
||||
|
||||
function bboxOfPoints(pts) {
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
|
||||
for (const p of pts) {
|
||||
if (p.x < minX) minX = p.x
|
||||
if (p.y < minY) minY = p.y
|
||||
if (p.x > maxX) maxX = p.x
|
||||
if (p.y > maxY) maxY = p.y
|
||||
}
|
||||
return { x: minX, y: minY, w: Math.max(0, maxX - minX), h: Math.max(0, maxY - minY) }
|
||||
}
|
||||
|
||||
/** 用一条路径替换当前选区(纯视图操作,不进历史) */
|
||||
function applyPath(kind, outlinePath, bbox, opts) {
|
||||
const o = opts || {}
|
||||
const feather = clamp(Number(S.selectionFeather) || 0, 0, 20)
|
||||
const inverted = !!o.inverted
|
||||
const path = new Path2D()
|
||||
if (inverted) {
|
||||
path.rect(0, 0, S.imgW, S.imgH)
|
||||
path.addPath(outlinePath)
|
||||
} else {
|
||||
path.addPath(outlinePath)
|
||||
}
|
||||
S.selection = {
|
||||
kind, path, outlinePath, bbox,
|
||||
fillRule: inverted ? 'evenodd' : 'nonzero',
|
||||
feather, inverted, active: true
|
||||
}
|
||||
S.marquee = null
|
||||
S.lassoPts = null
|
||||
S.interaction = 'idle'
|
||||
if (S.renderAll) S.renderAll()
|
||||
else renderSelection()
|
||||
toast(inverted ? '已反选' : '选区 ' + Math.round(bbox.w) + '×' + Math.round(bbox.h), 'info')
|
||||
}
|
||||
|
||||
export function clearMarquee() {
|
||||
S.selection = null
|
||||
S.marquee = null
|
||||
S.lassoPts = null
|
||||
S.interaction = 'idle'
|
||||
renderSelection()
|
||||
syncAnts()
|
||||
if (S.renderAll) S.renderAll()
|
||||
}
|
||||
|
||||
export function selectAll() {
|
||||
const b = { x: 0, y: 0, w: S.imgW, h: S.imgH }
|
||||
applyPath('rect', pathForBox(b, 'rect'), b)
|
||||
}
|
||||
|
||||
export function invertSelection() {
|
||||
if (!hasSelection()) { toast('先框出一个选区'); return }
|
||||
applyPath(S.selection.kind, S.selection.outlinePath, S.selection.bbox, { inverted: !S.selection.inverted })
|
||||
}
|
||||
|
||||
// ============ 鼠标交互(由 events.js 转发) ============
|
||||
function marqueeBox() {
|
||||
const m = S.marquee
|
||||
return rectFromPoints(m.x0, m.y0, m.x1, m.y1)
|
||||
}
|
||||
|
||||
export function beginMarquee(pos) {
|
||||
S.selection = null
|
||||
S.marquee = { x0: pos.x, y0: pos.y, x1: pos.x, y1: pos.y }
|
||||
S.interaction = 'marquee'
|
||||
S.isDrawing = true
|
||||
renderSelection()
|
||||
}
|
||||
|
||||
export function updateMarquee(pos) {
|
||||
if (!S.marquee) return
|
||||
S.marquee.x1 = pos.x
|
||||
S.marquee.y1 = pos.y
|
||||
renderSelection()
|
||||
}
|
||||
|
||||
export function endMarquee() {
|
||||
const m = S.marquee
|
||||
if (!m) return
|
||||
const b = marqueeBox()
|
||||
S.marquee = null
|
||||
S.isDrawing = false
|
||||
S.interaction = 'idle'
|
||||
if (b.w > 3 && b.h > 3) {
|
||||
applyPath(S.selectionKind, pathForBox(b, S.selectionKind), b)
|
||||
} else {
|
||||
clearMarquee()
|
||||
}
|
||||
}
|
||||
|
||||
export function beginLasso(pos) {
|
||||
S.selection = null
|
||||
S.lassoPts = [{ x: pos.x, y: pos.y }]
|
||||
S.interaction = 'lasso'
|
||||
S.isDrawing = true
|
||||
renderSelection()
|
||||
}
|
||||
|
||||
export function updateLasso(pos) {
|
||||
if (!S.lassoPts) return
|
||||
const last = S.lassoPts[S.lassoPts.length - 1]
|
||||
if (Math.hypot(pos.x - last.x, pos.y - last.y) < 2) return
|
||||
S.lassoPts.push({ x: pos.x, y: pos.y })
|
||||
renderSelection()
|
||||
}
|
||||
|
||||
export function endLasso() {
|
||||
const pts = S.lassoPts
|
||||
if (!pts) return
|
||||
S.lassoPts = null
|
||||
S.isDrawing = false
|
||||
S.interaction = 'idle'
|
||||
if (pts.length > 2) {
|
||||
const b = bboxOfPoints(pts)
|
||||
if (b.w > 3 && b.h > 3) { applyPath('lasso', pathForLasso(pts), b); return }
|
||||
}
|
||||
clearMarquee()
|
||||
}
|
||||
|
||||
// ============ 局部掩膜(羽化软边) ============
|
||||
/**
|
||||
* 返回覆盖 bbox 的 alpha 掩膜(局部 tile,不是全幅)。
|
||||
* feather>0 用 Canvas2D 原生 filter 模糊填充边缘,CSP 不限制。
|
||||
*/
|
||||
function buildMask() {
|
||||
const sel = S.selection
|
||||
const feather = sel.feather || 0
|
||||
const pad = Math.ceil(feather * 2)
|
||||
const b = sel.bbox
|
||||
const w = Math.max(1, Math.ceil(b.w) + pad * 2)
|
||||
const h = Math.max(1, Math.ceil(b.h) + pad * 2)
|
||||
const c = document.createElement('canvas')
|
||||
c.width = w
|
||||
c.height = h
|
||||
const cx = c.getContext('2d')
|
||||
cx.save()
|
||||
cx.translate(-b.x + pad, -b.y + pad)
|
||||
if (feather > 0) cx.filter = 'blur(' + feather + 'px)'
|
||||
cx.fillStyle = '#ffffff'
|
||||
cx.fill(sel.path, sel.fillRule)
|
||||
cx.restore()
|
||||
return { canvas: c, x: Math.floor(b.x) - pad, y: Math.floor(b.y) - pad, w, h }
|
||||
}
|
||||
|
||||
function writableLayer() {
|
||||
const layer = getActiveLayer()
|
||||
if (!layer || layer.locked) {
|
||||
toast(layer && layer.locked ? '当前图层已锁定,请先解锁' : '没有可用的图层', 'warn')
|
||||
return null
|
||||
}
|
||||
return layer
|
||||
}
|
||||
|
||||
/** 清除当前图层在选区内的像素(用户裁定:Delete 只作用单层,不动其它层) */
|
||||
function eraseOnActiveLayer() {
|
||||
const layer = writableLayer()
|
||||
if (!layer) return false
|
||||
const mask = buildMask()
|
||||
layer.ctx.save()
|
||||
layer.ctx.globalCompositeOperation = 'destination-out'
|
||||
layer.ctx.drawImage(mask.canvas, mask.x, mask.y)
|
||||
layer.ctx.restore()
|
||||
layer._bounds = undefined
|
||||
S.pickerComposite = null
|
||||
mask.canvas.width = 0
|
||||
mask.canvas.height = 0
|
||||
return true
|
||||
}
|
||||
|
||||
/** 复制/剪切:按 bbox 做局部 tile,再生成一张全幅透明图层,原位置不变 */
|
||||
function copyToLayer(cut) {
|
||||
const layer = writableLayer()
|
||||
if (!layer) return false
|
||||
const mask = buildMask()
|
||||
const tile = document.createElement('canvas')
|
||||
tile.width = mask.w
|
||||
tile.height = mask.h
|
||||
const tctx = tile.getContext('2d')
|
||||
// 把当前层按「全局坐标 → tile 局部坐标」对齐后取像素
|
||||
tctx.drawImage(layer.canvas, -mask.x, -mask.y)
|
||||
tctx.globalCompositeOperation = 'destination-in'
|
||||
tctx.drawImage(mask.canvas, 0, 0)
|
||||
|
||||
const canvas = createLayerCanvas()
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||
ctx.drawImage(tile, mask.x, mask.y)
|
||||
const id = 'S' + Date.now() + Math.floor(Math.random() * 1000)
|
||||
const fresh = {
|
||||
id,
|
||||
name: cut ? '剪切内容' : '选区副本',
|
||||
canvas, ctx,
|
||||
opacity: 1, visible: true, locked: false,
|
||||
transformable: true,
|
||||
x: 0, y: 0, w: S.imgW, h: S.imgH, rotation: 0,
|
||||
z: ++S.zCounter
|
||||
}
|
||||
S.layers.push(fresh)
|
||||
if (cut) eraseOnActiveLayer()
|
||||
reorderLayerCanvas()
|
||||
updateLayerCanvasStyles()
|
||||
setActiveLayer(id)
|
||||
for (const l of S.layers) l._bounds = undefined
|
||||
tile.width = 0; tile.height = 0
|
||||
mask.canvas.width = 0; mask.canvas.height = 0
|
||||
S.pickerComposite = null
|
||||
return true
|
||||
}
|
||||
|
||||
/** 用当前前景色填充选区(只作用当前层) */
|
||||
function fillOnActiveLayer() {
|
||||
const layer = writableLayer()
|
||||
if (!layer) return false
|
||||
const sel = S.selection
|
||||
layer.ctx.save()
|
||||
if (sel.feather > 0) layer.ctx.filter = 'blur(' + sel.feather + 'px)'
|
||||
layer.ctx.globalAlpha = S.brushOpacity
|
||||
layer.ctx.fillStyle = S.color
|
||||
layer.ctx.fill(sel.path, sel.fillRule)
|
||||
layer.ctx.restore()
|
||||
layer._bounds = undefined
|
||||
S.pickerComposite = null
|
||||
return true
|
||||
}
|
||||
|
||||
// ============ 命令注册(浮动条 / 右键 / 快捷键共用) ============
|
||||
// 显式在 open() 时注册,而不是模块顶层副作用:本模块与 commands.js / layers.js
|
||||
// 处在同一个 ESM 循环里,顶层访问 COMMANDS 可能撞上未初始化的绑定。
|
||||
let registered = false
|
||||
export function registerSelectionCommands() {
|
||||
if (registered) return
|
||||
registered = true
|
||||
defineCommand('sel.copy', {
|
||||
label: '复制为新层', enabled: hasSelection, hint: '先框出一个选区',
|
||||
run: () => { if (copyToLayer(false)) toast('已复制到新图层', 'success') }
|
||||
})
|
||||
defineCommand('sel.cut', {
|
||||
label: '剪切到新层', enabled: hasSelection, hint: '先框出一个选区',
|
||||
run: () => { if (copyToLayer(true)) toast('已剪切到新图层', 'success') }
|
||||
})
|
||||
defineCommand('sel.delete', {
|
||||
label: '清除选区内容(当前层)', enabled: hasSelection, hint: '先框出一个选区',
|
||||
run: () => { if (eraseOnActiveLayer()) toast('已清除当前层选区内容', 'success') }
|
||||
})
|
||||
defineCommand('sel.fill', {
|
||||
label: '填充选区', enabled: hasSelection, hint: '先框出一个选区',
|
||||
run: () => { if (fillOnActiveLayer()) toast('已填充', 'success') }
|
||||
})
|
||||
defineCommand('sel.invert', { label: '反选', view: true, run: invertSelection })
|
||||
defineCommand('sel.all', { label: '全选', view: true, run: selectAll })
|
||||
defineCommand('sel.none', { label: '取消选区', view: true, run: clearMarquee })
|
||||
}
|
||||
|
||||
/** 给外部(快捷键/菜单)一行调用 */
|
||||
export function runSelectionCommand(name) { return runCommand(name) }
|
||||
|
||||
/** 供 tools.js 限制画笔/橡皮(选区激活时只画在选区内) */
|
||||
export function applySelectionClip(ctx) {
|
||||
if (!hasSelection()) return false
|
||||
ctx.clip(S.selection.path, S.selection.fillRule)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 编辑器关闭时清理动画与临时画布 */
|
||||
export function disposeSelection() {
|
||||
if (S._antFrame) cancelAnimationFrame(S._antFrame)
|
||||
S._antFrame = 0
|
||||
S.selection = null
|
||||
S.marquee = null
|
||||
S.lassoPts = null
|
||||
clearSelectionCanvas()
|
||||
clearCursorCanvas()
|
||||
clearOverlay()
|
||||
}
|
||||
|
||||
/** 屏幕坐标 → 选区命中(右键菜单用) */
|
||||
export function hitSelectionAtEvent(e) {
|
||||
if (!hasSelection() || !S.selectionCtx) return false
|
||||
const p = getPos(e)
|
||||
try {
|
||||
return S.selectionCtx.isPointInPath(S.selection.path, p.x, p.y, S.selection.fillRule)
|
||||
} catch (err) { return false }
|
||||
}
|
||||
@@ -76,7 +76,24 @@
|
||||
callbacks: null,
|
||||
spaceDown: false,
|
||||
_shiftDown: false,
|
||||
_canvasEventsBound: false
|
||||
_canvasEventsBound: false,
|
||||
|
||||
// ---- v1.1 选区 / 便利性 ----
|
||||
selection: null, // { kind, path, bbox, feather, active, fillRule, outline }
|
||||
marquee: null, // 拉框中的临时选区 { x0,y0,x1,y1,kind }
|
||||
lassoPts: null, // 套索绘制中的点序列
|
||||
selectionKind: 'rect', // 选区工具的形状:rect | ellipse
|
||||
selectionFeather: 0, // 羽化 px(0~20)
|
||||
selectionCanvas: null, // 蚂蚁线专用层(与 overlay 分离,互不擦除)
|
||||
selectionCtx: null,
|
||||
cursorCanvas: null, // 笔刷环专用层
|
||||
cursorCtx: null,
|
||||
_antFrame: 0, // 蚂蚁线 rAF 句柄
|
||||
_antOffset: 0,
|
||||
exportOptions: null, // { preset, format, bg, maxKB, size },来自 ctx.settings
|
||||
interaction: 'idle', // 轻量交互状态机:idle | marquee | lasso | placing | cropping
|
||||
renderAll: null, // 由 index.js 注入的统一重绘出口
|
||||
lastExport: null // 观测口:{ bytes, width, height, format, preset }
|
||||
}
|
||||
|
||||
export const runtime = { el: null }
|
||||
@@ -77,6 +77,7 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
|
||||
const ctx = getActiveCtx()
|
||||
if (!ctx) return
|
||||
ctx.save()
|
||||
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
|
||||
ctx.globalCompositeOperation = 'destination-out'
|
||||
ctx.globalAlpha = S.brushOpacity
|
||||
ctx.lineWidth = Math.max(1, S.brushSize)
|
||||
@@ -135,6 +136,7 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
|
||||
const ctx = getActiveCtx()
|
||||
if (!ctx) return
|
||||
ctx.save()
|
||||
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
|
||||
if (S.tool === 'eraser') {
|
||||
ctx.globalCompositeOperation = 'destination-out'
|
||||
}
|
||||
@@ -216,10 +218,22 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
|
||||
return rect.width ? rect.width / S.imgW : S.zoom
|
||||
}
|
||||
|
||||
/** 圆形笔刷光标 */
|
||||
/** 清笔刷环专用层(不碰裁剪框 / 选中框 / 蚂蚁线) */
|
||||
export function clearToolRing() {
|
||||
const ctx = S.cursorCtx
|
||||
if (!ctx) return
|
||||
const pad = S.overlayPad || 0
|
||||
ctx.save()
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
|
||||
ctx.restore()
|
||||
ctx.setTransform(1, 0, 0, 1, pad, pad)
|
||||
}
|
||||
|
||||
/** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */
|
||||
export function drawToolRing(pos) {
|
||||
clearOverlay()
|
||||
const ctx = S.overlayCtx
|
||||
clearToolRing()
|
||||
const ctx = S.cursorCtx || S.overlayCtx
|
||||
const r = getToolBrushRadius()
|
||||
const k = 1 / screenScale()
|
||||
const rMin = 2 * k
|
||||
@@ -348,6 +362,13 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
|
||||
if (tool !== 'select' && tool !== 'pen') { S.penEditId = null; S.penDragPt = -1; S.penDragPending = null }
|
||||
if (tool === 'picker' && S.tool !== 'picker') S.prevTool = S.tool
|
||||
if (tool !== 'pen') S.penPath = null
|
||||
// 选区与裁剪互斥:进裁剪必须清掉选区;离开选区工具要丢弃未完成的拉框/套索
|
||||
if (tool === 'crop') { S.selection = null; S.marquee = null; S.lassoPts = null }
|
||||
if (tool !== 'marquee' && tool !== 'lasso') {
|
||||
if (S.marquee || S.lassoPts) { S.isDrawing = false; S.interaction = 'idle' }
|
||||
S.marquee = null
|
||||
S.lassoPts = null
|
||||
}
|
||||
S.tool = tool
|
||||
if (tool !== 'select') S.selectedLayerId = null
|
||||
if (tool !== 'text' && tool !== 'select') S.selectedTextId = null
|
||||
@@ -368,4 +389,6 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
|
||||
}
|
||||
renderObjects()
|
||||
renderLayerPanel()
|
||||
// 让蚂蚁线/浮动条按新的工具与选区状态同步(由 index.js 注入)
|
||||
if (S.renderAll) S.renderAll()
|
||||
}
|
||||
@@ -15,13 +15,19 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
|
||||
|
||||
// ============ 画布设置 ============
|
||||
|
||||
/** 三张交互层(选中框/蚂蚁线/笔刷环)共享同一尺寸与坐标基准,但各自清屏互不影响 */
|
||||
function syncOverlayCanvas() {
|
||||
const pad = S.overlayPad || 0
|
||||
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
|
||||
S.overlayCanvas.style.left = '0px'
|
||||
S.overlayCanvas.style.top = '0px'
|
||||
S.overlayCanvas.style.width = Math.round((S.imgW + pad * 2) * scale) + 'px'
|
||||
S.overlayCanvas.style.height = Math.round((S.imgH + pad * 2) * scale) + 'px'
|
||||
const w = Math.round((S.imgW + pad * 2) * scale) + 'px'
|
||||
const h = Math.round((S.imgH + pad * 2) * scale) + 'px'
|
||||
for (const c of [S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
|
||||
if (!c) continue
|
||||
c.style.left = '0px'
|
||||
c.style.top = '0px'
|
||||
c.style.width = w
|
||||
c.style.height = h
|
||||
}
|
||||
}
|
||||
|
||||
export function setupCanvas(img) {
|
||||
@@ -40,9 +46,12 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
|
||||
S.strokeCanvas.style.display = 'none'
|
||||
// 裁剪越界区域属于交互工作区,不改变图片本身的画布尺寸。
|
||||
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
|
||||
S.overlayCanvas.width = S.imgW + S.overlayPad * 2
|
||||
S.overlayCanvas.height = S.imgH + S.overlayPad * 2
|
||||
S.overlayCtx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
|
||||
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)
|
||||
}
|
||||
|
||||
// 创建图层 1: 原图
|
||||
const baseCanvas = createLayerCanvas()
|
||||
|
||||
@@ -72,6 +72,7 @@ export function createGlue(ctx, css) {
|
||||
Promise.resolve(editor.open({
|
||||
imageBase64: image.dataUrl,
|
||||
imageName: baseName(node) + '.png',
|
||||
settings: ctx.settings, // 记住输出预设 / 侧栏开合(宿主提供的命名空间 KV)
|
||||
onError: function (message) {
|
||||
settle(function () { reject(new Error(String(message || '编辑失败'))) })
|
||||
},
|
||||
|
||||
@@ -12,4 +12,12 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
version: '__PLUGIN_VERSION__',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
exportPreset: { type: 'string', default: 'original' },
|
||||
exportFormat: { type: 'string', default: 'png' },
|
||||
exportBg: { type: 'string', default: 'transparent' },
|
||||
exportMaxKB: { type: 'number', default: 0 },
|
||||
exportSize: { type: 'number', default: 800 },
|
||||
panelsCollapsed: { type: 'boolean', default: false }
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user