459 lines
20 KiB
JavaScript
459 lines
20 KiB
JavaScript
/* IWB 图片编辑器 - 图层化裁剪与标注
|
||
* 独立模块,通过 window.__iwbEditor.open() 调用
|
||
* 接收 imageBase64,返回编辑后的 dataURL
|
||
*
|
||
* v2.0.0 特性:
|
||
* - 图层系统:位图图层动态管理(原图、画笔、导入图片),可调透明度、显隐、排序
|
||
* - 矢量对象(文字/形状)在图层面板中统一展示,z 序可调
|
||
* - 统一橡皮:一个橡皮擦除当前活跃位图图层,与画笔共用大小/透明度/软硬
|
||
* - 添加位图图层:支持导入新图片作为独立图层
|
||
* - 工具:选择 / 画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪
|
||
*
|
||
* 分层架构:
|
||
* - bitmap layers: 每个位图图层一个 canvas(动态创建/排序),CSS opacity 控制透明度
|
||
* - textCanvas: 矢量对象层(文字+形状),共享一个 canvas
|
||
* - strokeCanvas: 笔划预览层(一笔结束后合成进活跃图层)
|
||
* - overlayCanvas: 选中框/裁剪遮罩/笔刷预览
|
||
*/
|
||
|
||
/* index.js - 模块组装与对外接口
|
||
* 汇总各子模块,承载「打开编辑器 / 关闭 / 复原 / 输出」生命周期,
|
||
* 并把 window.__iwbEditor = { open, close, __stats } 挂到全局(对外唯一接口)。
|
||
* 注意:entries/content.js 必须先 import 本文件再 import content.js。
|
||
* 顶层只允许声明与这次 window 赋值,不调用其它模块的函数(避免循环 TDZ)。
|
||
*/
|
||
|
||
'use strict'
|
||
|
||
import { S, runtime } from './state.js'
|
||
import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotStats } from './history.js'
|
||
import { cancelImagePlacement } from './placement.js'
|
||
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
|
||
import { createEl, loadImage } from './dom.js'
|
||
import { renderObjects, hideTextInput, textBounds } from './objects.js'
|
||
import { setupCanvas } from './viewport.js'
|
||
import { resetOverlayTransform } from './scale.js'
|
||
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar, loadSideWidth, loadColorPopPinned } from './events.js'
|
||
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
|
||
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
|
||
import { renderFxPanel } from './effects.js'
|
||
import { adjustCacheSize, onHistoryRestore as onAdjustHistoryRestore, renderAdjustPanel, resetAdjustCache } from './adjust.js'
|
||
import { loadExportOptions, prepareOutput, downloadBlob, copyBlobToClipboard, bindExportUI, renderExportUI } from './export.js'
|
||
import { loadRecentColors } from './recent-colors.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
|
||
S.renderFxPanel = renderFxPanel
|
||
S.renderAdjustPanel = renderAdjustPanel
|
||
// 撤销/重做后调节参数必须归零(详见 adjust.js#onHistoryRestore 的注释)
|
||
S.onHistoryRestore = onAdjustHistoryRestore
|
||
|
||
try {
|
||
const img = await loadImage(options.imageBase64)
|
||
S.imgW = img.naturalWidth || img.width
|
||
S.imgH = img.naturalHeight || img.height
|
||
S.originalImage = img
|
||
runtime.el.style.display = 'flex'
|
||
S.open = true
|
||
S.zoom = 1
|
||
setupCanvas(img)
|
||
resetState()
|
||
updateAllUI()
|
||
registerSelectionCommands()
|
||
loadExportOptions()
|
||
loadRecentColors()
|
||
// v1.18:色板「钉住」状态也来自宿主 KV,和常用色/最近色一起恢复
|
||
loadColorPopPinned()
|
||
bindLiteUI()
|
||
bindFloating()
|
||
bindExportUI()
|
||
initPanels()
|
||
// 右栏宽度跟着用户上次拖的位置(v1.16);必须在 initPanels 之后——
|
||
// 侧栏收起时元素虽 display:none,写 CSS 变量仍然有效,下次展开直接生效
|
||
loadSideWidth()
|
||
renderAll()
|
||
} catch (e) {
|
||
console.error('[IWB编辑器] 打开失败:', e)
|
||
if (runtime.el) runtime.el.style.display = 'none'
|
||
if (options.onError) options.onError(e.message)
|
||
} finally {
|
||
// 源图字符串只在解码这一刻有用(loadImage 内已转 blob URL)。
|
||
// 不丢的话 S.callbacks 会在整个编辑会话持有整份 dataURL(4K ≈44MB),
|
||
// 打开失败路径更是会一直挂到下次打开才被覆盖。
|
||
options.imageBase64 = null
|
||
}
|
||
}
|
||
|
||
function resetState() {
|
||
purgeVectorCanvases()
|
||
S.history = []
|
||
S.redoStack = []
|
||
S.cropRect = null
|
||
S.cropHandle = null
|
||
S.cropMoving = false
|
||
S.moveStart = null
|
||
S.isDrawing = false
|
||
S.panning = false
|
||
S.tool = 'brush'
|
||
S.color = '#ff4444'
|
||
S.brushSize = 3
|
||
S.brushHardness = 100
|
||
S.brushOpacity = 1
|
||
S.prevTool = null
|
||
S.pickerComposite = null
|
||
S.rectFill = false
|
||
S.shapeLineWidth = 3
|
||
S.textSize = 32
|
||
S.cropConstraint = { type: 'free', ratio: 0, sizeW: 0, sizeH: 0 }
|
||
S.textLayers = []
|
||
S.selectedTextId = null
|
||
S.textDrag = null
|
||
S.textEditingId = null
|
||
S.shapeLayers = []
|
||
S.selectedShapeId = null
|
||
S.shapeDrag = null
|
||
S.penPath = null
|
||
S.penEditId = null
|
||
S.penDragPt = -1
|
||
S.penDragBase = null
|
||
S.penDragPending = null
|
||
// 编辑器 DOM 复用,重开时旧的位图选中 id 指向已删除的图层,必须清掉
|
||
S.selectedLayerId = null
|
||
S.bitmapDrag = null
|
||
// 跨会话残留:多选合并集合、悬停点、双击判定都会指向上一张图的图层
|
||
S.layerMulti.length = 0
|
||
S.hoverPos = null
|
||
S.lastClick = null
|
||
S.lastNameClick = null
|
||
S.altPicker = false
|
||
// 快速效果的基准像素属于上一张图,重开必须清掉(否则滑杆会往新图上写旧像素)
|
||
S.fx = { key: null, value: 0, layerId: null, source: null }
|
||
// 图片调节的基准像素同理,而且更致命:缓存 key 是图层 id,原图恒为 'base',
|
||
// 不清就一定命中上一张图的像素(v1.15.1 修「调新图变回旧图」)
|
||
resetAdjustCache()
|
||
S.zCounter = Math.max(S.layers.length - 1, 0)
|
||
S.placingImage = null
|
||
S.placingHandle = null
|
||
S.placingStart = null
|
||
const sizeToggle = runtime.el && runtime.el.querySelector('.iwb-editor-size-toggle')
|
||
if (sizeToggle) { sizeToggle.classList.remove('active'); sizeToggle.setAttribute('aria-pressed', 'false'); sizeToggle.textContent = '启用尺寸' }
|
||
// 重开时旧选区 / 蚂蚁线 / 浮动条不能残留
|
||
S.selection = null
|
||
S.marquee = null
|
||
S.lassoPts = null
|
||
S.interaction = 'idle'
|
||
S.lastExport = null
|
||
if (S._antFrame) { cancelAnimationFrame(S._antFrame); S._antFrame = 0 }
|
||
hideSelectionContext()
|
||
if (S.selectionCtx) renderSelection()
|
||
if (S.cursorCtx) {
|
||
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
|
||
S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height)
|
||
resetOverlayTransform(S.cursorCtx)
|
||
}
|
||
}
|
||
|
||
/** 命令层统一重绘出口:所有新操作的像素/UI/选区状态在这里对齐 */
|
||
function renderAll() {
|
||
if (!S.open || !runtime.el) return
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
renderFxPanel()
|
||
// 调节面板跟着图层走:新建/切换/删除图层都要刷新 target 与滑块值
|
||
renderAdjustPanel()
|
||
renderOptionBar()
|
||
updateStatusbar()
|
||
renderExportUI()
|
||
renderSelection()
|
||
syncAnts()
|
||
positionFloating()
|
||
}
|
||
|
||
/** 侧栏开合:记住上次选择,窄窗口默认收起(画布优先) */
|
||
function initPanels() {
|
||
if (!runtime.el) return
|
||
const st = S.callbacks && S.callbacks.settings
|
||
let saved = false
|
||
if (st && typeof st.get === 'function') { try { saved = !!st.get('panelsCollapsed') } catch (e) { /* ignore */ } }
|
||
const auto = (window.innerWidth || 1440) < 1100
|
||
runtime.el.classList.toggle('panels-collapsed', saved || auto)
|
||
}
|
||
|
||
/**
|
||
* 关闭编辑器。reason:'cancel'(用户点退出)| 'done'(导出成功后关闭)。
|
||
* 必须先通知宿主再置空 S.callbacks —— glue.js 的 openEditor() 只在
|
||
* onResult / onError / onClose 三处结算,「退出」曾经没有任何回调,宿主
|
||
* Promise 永远悬挂;回调异常不能阻断后面的内存释放。
|
||
*/
|
||
export function close(reason) {
|
||
const callbacks = S.callbacks
|
||
try {
|
||
if (callbacks && typeof callbacks.onClose === 'function') callbacks.onClose(reason || 'cancel')
|
||
} catch (e) {
|
||
console.error('[IWB编辑器] onClose 回调异常:', e)
|
||
}
|
||
if (runtime.el) {
|
||
hideTextInput()
|
||
runtime.el.style.display = 'none'
|
||
}
|
||
releaseEditorMemory()
|
||
S.open = false
|
||
S.callbacks = null
|
||
S.placingImage = null
|
||
S.placingHandle = null
|
||
S.placingStart = null
|
||
S.penPath = null
|
||
S.textEditingId = null
|
||
clearSelection()
|
||
hideSelectionContext()
|
||
disposeSelection()
|
||
}
|
||
|
||
/**
|
||
* 关闭即释放(对齐宿主「内存里不放大图」的模型):
|
||
* 此前 close() 只把遮罩 display:none,历史快照(≤128MB 的全幅 ImageData)、
|
||
* 各全幅图层/overlay canvas 的像素缓冲、原图 Image 与 base64 全部继续驻留 ——
|
||
* 编辑一张 4K 图后即使退出,堆里仍挂着 ~100MB,直到下次打开编辑器才被重建顶掉。
|
||
* 释放后下次 open() 由 setupCanvas + resetState 全量重建,无状态残留依赖。
|
||
*/
|
||
function releaseEditorMemory() {
|
||
// 1) 撤销/重做栈:像素快照是最大头
|
||
S.history = []
|
||
S.redoStack = []
|
||
// 2) 原图引用与吸管合成缓存(各为一张全幅位图)
|
||
S.originalImage = null
|
||
S.pickerComposite = null
|
||
// 2b) 快速效果的基准像素:又一张全幅位图,不释放就白占一份图大小的内存
|
||
S.fx = { key: null, value: 0, layerId: null, source: null }
|
||
// 2c) 图片调节的基准像素与预览副本(两张全幅位图)+ 按 layer.id 的缓存 Map。
|
||
// 缓存必须清,否则下次打开新图时 'base' 会命中这份旧像素(v1.15.1)
|
||
resetAdjustCache()
|
||
// 3) 交互态复位:关闭后 window mouseup 等全局监听仍活着,靠标志位保证不落到绘制路径
|
||
S.isDrawing = false
|
||
S.panning = false
|
||
S.penDragPt = -1
|
||
S.penDragPending = null
|
||
S.placingImage = null
|
||
S.placingHandle = null
|
||
S.placingStart = null
|
||
// 4) 位图图层(含 sourceCanvas):置 0 释放像素缓冲并从 DOM 摘除;
|
||
// setupCanvas 依赖 S.layers 做清理,这里必须同步清空,避免下次打开残留旧 canvas
|
||
for (const layer of S.layers) {
|
||
try {
|
||
if (layer.sourceCanvas) { layer.sourceCanvas.width = 0; layer.sourceCanvas.height = 0 }
|
||
if (layer.canvas) {
|
||
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
|
||
layer.canvas.width = 0
|
||
layer.canvas.height = 0
|
||
}
|
||
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
|
||
}
|
||
S.layers = []
|
||
// 5) 工作 canvas:text / stroke / overlay(overlay 含 18% 交互边距,4K 图约 74MB)
|
||
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
|
||
try { if (c) { c.width = 0; c.height = 0 } } catch (e) { /* ignore */ }
|
||
}
|
||
// 6) 矢量对象的画布缓存
|
||
purgeVectorCanvases()
|
||
}
|
||
|
||
// ============ 输出 ============
|
||
/**
|
||
* 导出:合成 → PNG 字节 → onResult(out, mode) → close()。
|
||
* 用 toBlob 而非 toDataURL —— 编码结果落在浏览器 Blob 存储(堆外),
|
||
* 省掉全幅 base64 字符串(4K 图约 44MB JS 堆驻留);onResult 收到 Blob 或 dataURL 均可。
|
||
*/
|
||
/**
|
||
* 单张输出:prepareOutput() 负责合成 → 尺寸/背景 → 编码(含 ≤500KB 降质)。
|
||
* 一次只产出一个结果;download 只下载、不关编辑器、不回写宿主节点。
|
||
*/
|
||
export async function exportResult(mode) {
|
||
if (S.placingImage) cancelImagePlacement()
|
||
try {
|
||
const { blob } = await prepareOutput()
|
||
if (mode === 'download') {
|
||
downloadBlob(blob)
|
||
// download 不关编辑器:必须走一次统一重绘,摘要的「上次输出 …KB」才会更新
|
||
if (S.renderAll) S.renderAll()
|
||
return
|
||
}
|
||
if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode)
|
||
close('done')
|
||
} catch (e) {
|
||
console.error('[IWB编辑器] 导出失败:', e)
|
||
toast('导出失败:' + ((e && e.message) || '图片可能跨域'), 'error')
|
||
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('导出失败:' + ((e && e.message) || '图片跨域'))
|
||
}
|
||
}
|
||
|
||
/** 复制当前结果为图片到系统剪贴板:不关编辑器、不写宿主节点 */
|
||
export async function copyResult() {
|
||
if (S.placingImage) cancelImagePlacement()
|
||
try {
|
||
const { blob } = await prepareOutput()
|
||
await copyBlobToClipboard(blob)
|
||
if (S.renderAll) S.renderAll() // 摘要里的「上次输出 …KB」要跟上
|
||
} catch (e) {
|
||
console.error('[IWB编辑器] 复制失败:', e)
|
||
toast('复制失败:' + ((e && e.message) || '图片可能跨域'), 'error')
|
||
}
|
||
}
|
||
|
||
// ============ 暴露接口 ============
|
||
/**
|
||
* 快照/历史开销观测口(性能回归与手测用):
|
||
* history / redo 当前栈深度与占用字节
|
||
* snapshots 快照次数
|
||
* getImageDataCalls 累计全幅像素读取次数(优化前后最直观的对比指标)
|
||
* bytesWritten 累计拍摄的像素字节数
|
||
*/
|
||
export const __stats = () => ({
|
||
history: S.history.length,
|
||
historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0),
|
||
redo: S.redoStack.length,
|
||
redoBytes: S.redoStack.reduce((n, s) => n + (s.__bytes || 0), 0),
|
||
maxEntries: HISTORY_MAX_ENTRIES,
|
||
maxBytes: HISTORY_MAX_BYTES,
|
||
historyBudget: historyBudgetBytes(),
|
||
...snapshotStats
|
||
})
|
||
|
||
/** 开发/回归观测口:本地探针与真站 e2e 用它断言图层、选区与像素,不参与业务逻辑 */
|
||
const __debug = () => ({
|
||
open: S.open,
|
||
tool: S.tool,
|
||
color: S.color,
|
||
altPicker: !!S.altPicker,
|
||
doc: { w: S.imgW, h: S.imgH },
|
||
zoom: S.zoom,
|
||
fit: { w: Math.round(S.fitW || 0), h: Math.round(S.fitH || 0) },
|
||
layers: S.layers.map(l => ({
|
||
id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false,
|
||
// 不透明度有两个面:数据字段(导出/合并用)与 CSS(屏幕上看到的),两者必须一致
|
||
opacity: l.opacity == null ? 1 : l.opacity,
|
||
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null
|
||
})),
|
||
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, strokeOn: s.strokeOn !== false, z: s.z, color: s.color, fillColor: s.fillColor || null, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
|
||
texts: S.textLayers.map(t => ({
|
||
id: t.id, text: t.text, x: t.x, y: t.y, fontSize: t.fontSize, color: t.color,
|
||
fontWeight: t.fontWeight, fontFamily: t.fontFamily, align: t.align, lineHeight: t.lineHeight,
|
||
strokeWidth: t.strokeWidth, strokeColor: t.strokeColor, bgFill: !!t.bgFill, bgColor: t.bgColor,
|
||
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
|
||
box: (() => { const b = textBounds(t); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) } })()
|
||
})),
|
||
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
|
||
guides: S.guides ? S.guides.map(g => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
|
||
recentColors: (S.recentColors || []).slice(),
|
||
textDefaults: {
|
||
weight: S.textWeight, family: S.textFamily, align: S.textAlign, lineHeight: S.textLineHeight,
|
||
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
|
||
bgFill: S.textBgFill, bgColor: S.textBgColor, bgAlpha: S.textBgAlpha
|
||
},
|
||
// 矢量图形颜色:fillColor=null 表示跟随描边色(回归要能断言这条语义)
|
||
shapeColors: { stroke: S.color, fill: S.shapeFillColor || null },
|
||
// 色板当前在调哪一格:stroke / fill / bg(文字上下文里 fill=描边、bg=底色)
|
||
colorTarget: S.colorTarget,
|
||
selectedShapeId: S.selectedShapeId,
|
||
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
|
||
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
|
||
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
|
||
drag: S.shapeDrag ? ('shape:' + S.shapeDrag.mode + (S.shapeDrag.handle ? ':' + S.shapeDrag.handle : ''))
|
||
: S.textDrag ? ('text:' + S.textDrag.mode)
|
||
: S.bitmapDrag ? ('bitmap:' + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ':' + S.bitmapDrag.handle : ''))
|
||
: null,
|
||
selectedTextId: S.selectedTextId,
|
||
penEditId: S.penEditId,
|
||
activeLayerId: S.activeLayerId,
|
||
selectedLayerId: S.selectedLayerId,
|
||
layerMulti: S.layerMulti.map(x => x.type + ':' + x.id),
|
||
selection: selectionInfo(),
|
||
toolOptions: {
|
||
brushSize: S.brushSize,
|
||
brushHardness: S.brushHardness,
|
||
brushOpacity: S.brushOpacity,
|
||
shapeLineWidth: S.shapeLineWidth,
|
||
textSize: S.textSize,
|
||
rectFill: S.rectFill,
|
||
penFill: S.penFill
|
||
},
|
||
history: S.history.length,
|
||
historyLabels: S.history.map(s => s.__label || ''),
|
||
redo: S.redoStack.length,
|
||
exportOptions: S.exportOptions ? { ...S.exportOptions } : null,
|
||
lastExport: S.lastExport ? { ...S.lastExport } : null,
|
||
// 快速效果的可重调状态:hasSource=false 表示还没点过效果(滑杆应置灰)
|
||
fx: { key: S.fx.key, value: S.fx.value, layerId: S.fx.layerId, hasSource: Boolean(S.fx.source) },
|
||
// v1.15 图片调节:params 是 11 项当前值,hasSource 决定面板是否可用
|
||
adjust: {
|
||
layerId: S.adjust ? S.adjust.layerId : null,
|
||
hasSource: Boolean(S.adjust && S.adjust.source),
|
||
params: S.adjust && S.adjust.params ? { ...S.adjust.params } : null
|
||
},
|
||
// 调节基准缓存条数:退出编辑器后必须是 0(否则下一张图会拿到上一张的像素)
|
||
adjustCacheSize: adjustCacheSize(),
|
||
interaction: S.interaction,
|
||
ants: !!S._antFrame,
|
||
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null,
|
||
// 图层整幅像素指纹(抽样校验和):断言「改强度后从基准重算」而不是叠加,
|
||
// 比逐点采样稳 —— 马赛克/模糊的差异散在整幅,单点可能刚好相同
|
||
layerHash: (id) => {
|
||
const l = S.layers.find(v => v.id === id)
|
||
if (!l || !l.ctx || !l.canvas) return 0
|
||
try {
|
||
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
|
||
let h = 2166136261
|
||
for (let i = 0; i < d.length; i += 97) {
|
||
h ^= d[i]
|
||
h = Math.imul(h, 16777619)
|
||
}
|
||
return h >>> 0
|
||
} catch (e) { return 0 }
|
||
},
|
||
// 非透明像素的平均色:断言效果是否落在预期值上(如反相 50% 必然趋近 128)
|
||
avgColor: (id) => {
|
||
const l = S.layers.find(v => v.id === id)
|
||
if (!l || !l.ctx || !l.canvas) return null
|
||
try {
|
||
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
|
||
let r = 0, g = 0, b = 0, n = 0
|
||
for (let i = 0; i < d.length; i += 4) {
|
||
if (d[i + 3] < 200) continue
|
||
r += d[i]; g += d[i + 1]; b += d[i + 2]; n++
|
||
}
|
||
return n ? [Math.round(r / n), Math.round(g / n), Math.round(b / n), n] : null
|
||
} catch (e) { return null }
|
||
},
|
||
pixel: (id, x, y) => {
|
||
const l = S.layers.find(v => v.id === id)
|
||
if (!l || !l.ctx) return null
|
||
try { return Array.from(l.ctx.getImageData(Math.round(x), Math.round(y), 1, 1).data) } catch (e) { return null }
|
||
},
|
||
// 区域透明像素统计:断言「合并后两半都有内容」比逐点采样快一个量级
|
||
alphaIn: (id, x0, y0, x1, y1) => {
|
||
const l = S.layers.find(v => v.id === id)
|
||
if (!l || !l.ctx) return 0
|
||
try {
|
||
const w = Math.max(1, Math.round(x1 - x0))
|
||
const h = Math.max(1, Math.round(y1 - y0))
|
||
const d = l.ctx.getImageData(Math.round(x0), Math.round(y0), w, h).data
|
||
let n = 0
|
||
for (let i = 3; i < d.length; i += 4) if (d[i] > 0) n++
|
||
return n
|
||
} catch (e) { return 0 }
|
||
}
|
||
})
|
||
|
||
window.__iwbEditor = {
|
||
open,
|
||
close,
|
||
__stats,
|
||
__debug
|
||
}
|