/* 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 { resetOverlayTransform, viewScale } from './scale.js' import { clearOverlay } from './crop.js' import { defineCommand, runCommand, toast } from './commands.js' import { createLayerCanvas, ensureWritableLayer, 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, inverted: !!S.selection.inverted } } // ============ 选区图层(独立 canvas) ============ /** 清 selectionCanvas(与 crop.js#clearOverlay 同一坐标基准,但互不干扰) */ function clearSelectionCanvas() { const ctx = S.selectionCtx if (!ctx) return ctx.save() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) ctx.restore() resetOverlayTransform(ctx) } export function clearCursorCanvas() { const ctx = S.cursorCtx if (!ctx) return ctx.save() ctx.setTransform(1, 0, 0, 1, 0, 0) ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) ctx.restore() resetOverlayTransform(ctx) } /** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */ export function renderSelection() { if (!S.selectionCtx) return clearSelectionCanvas() const ctx = S.selectionCtx const k = 1 / Math.max(viewScale(), 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) } // 建立像素选区即接管 Delete 语义:清掉矢量对象选中态,否则 // 「选中形状 → Ctrl+A → Delete」会走删对象分支,而不是清像素。 S.selectedTextId = null S.selectedShapeId = null 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() } // ============ 局部掩膜(羽化软边) ============ /** * 掩膜必须覆盖的范围(整数基准,避免 tile 原点与平移量差 1px)。 * 反选的 path 是「整图矩形 + 原选区」,只按原 bbox 开 tile 会把 tile 之外 * 的反选区域整块丢掉 —— 填充走全幅 fill(path) 不受影响,于是 Delete/复制/剪切 * 只作用原 bbox,与填充互相矛盾。反选时扩成整幅,临时画布用完即弃。 */ function maskExtent() { const sel = S.selection const b = sel.inverted ? { x: 0, y: 0, w: S.imgW, h: S.imgH } : sel.bbox const x = Math.floor(b.x) const y = Math.floor(b.y) return { x, y, w: Math.max(1, Math.ceil(b.x + b.w) - x), h: Math.max(1, Math.ceil(b.y + b.h) - y) } } /** * 返回覆盖 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 e = maskExtent() const w = e.w + pad * 2 const h = e.h + pad * 2 const c = document.createElement('canvas') c.width = w c.height = h const cx = c.getContext('2d') cx.save() cx.translate(-e.x + pad, -e.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: e.x - pad, y: e.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 } /** 用当前前景色填充选区(只作用当前层)。 * 填充是「加内容」的操作:当前层锁定(默认只剩原图)时自动落「标注」层, * 与画笔的兜底一致;Delete/剪切是「减内容」,保持提示不自动建层。 */ function fillOnActiveLayer() { const layer = ensureWritableLayer() 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 } }