/* layers.js - 位图图层管理、矢量对象画布与图层面板 * 节:图层管理、矢量对象独立画布(位图/矢量统一排序)、图层面板 UI, * 外加原属「图片放置」节末尾的 deleteLayer。 * 约定:位图图层一个 canvas,矢量对象(文字/形状)各自独立 canvas, * reorderLayerCanvas 按 z 统一排序插入 S.canvasStack。 */ 'use strict' import { S, runtime } from './state.js' import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js' import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js' import { drawShape } from './tools.js' import { saveSnapshot, snapshotState } from './history.js' import { placeImageDirectly } from './placement.js' import { updateBrushParamUI, updateColorUI } from './events.js' import { isDrawableLayer } from '../vendor/layer-logic.js' // ============ 图层管理 ============ /** 创建位图图层 canvas 元素并插入 DOM 栈 */ export function createLayerCanvas() { const c = document.createElement('canvas') c.className = 'iwb-editor-layer-canvas' c.width = S.imgW c.height = S.imgH c.style.position = 'absolute' c.style.top = '0' c.style.left = '0' c.style.display = 'block' // 插入到 strokeCanvas 之前(位图图层在矢量层之下) S.canvasStack.insertBefore(c, S.strokeCanvas) return c } /** 按图层 z 序重排 DOM 中的 canvas 元素。 * 所有 canvas 必须共享 canvas-stack 的坐标系;隐藏图层只用 CSS 隐藏, * 不从 DOM 移除,避免 canvas-stack 在 flex/inline 布局下重新计算位置。 */ export function reorderLayerCanvas() { // 与合成/导出/面板/命中测试共用同一份 z 序,杜绝「面板顺序 ≠ 实际叠放」 for (const u of layerUnits()) { const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas // 快照恢复后的矢量对象可能带着被 JSON 序列化过的伪画布({}),必须挡住 if (!el || el.nodeType !== 1) continue S.canvasStack.insertBefore(el, S.strokeCanvas) el.style.display = u.obj.visible === false ? 'none' : 'block' } } /** 获取活跃位图图层 */ export function getActiveLayer() { return S.layers.find(l => l.id === S.activeLayerId) || null } /** 获取活跃位图图层的 2d context(画笔/橡皮操作目标) */ export function getActiveCtx() { const layer = getActiveLayer() return layer && !layer.locked ? layer.ctx : null } /** 清理所有画布/图层选择态,保证不同工具和图层之间互斥 */ export function clearSelection({ keepBitmap = false } = {}) { if (!keepBitmap) S.selectedLayerId = null S.selectedTextId = null S.selectedShapeId = null S.textDrag = null S.shapeDrag = null S.bitmapDrag = null } /** 确定源图/源画布的取样框:内容盒 _srcBox 优先,其次整图 image,再其次整张 sourceCanvas;无可用源返回 null */ function resolveSourceBox(layer) { if (layer._srcBox && layer.sourceCanvas) { const b = layer._srcBox return { src: layer.sourceCanvas, box: b } } if (layer.image && layer.w > 0 && layer.h > 0) return { src: layer.image, box: null } if (layer.sourceCanvas && layer.w > 0 && layer.h > 0) return { src: layer.sourceCanvas, box: null } return null } /** 带变换绘制:按图层旋转角施加变换后把取样源画到图层画布(无源时只应用变换不落笔) */ function paintTransformed(layer, source) { const rot = layer.rotation || 0 const cx = layer.x + layer.w / 2, cy = layer.y + layer.h / 2 layer.ctx.save() if (rot) { layer.ctx.translate(cx, cy) layer.ctx.rotate(rot * Math.PI / 180) layer.ctx.translate(-cx, -cy) } if (source) { if (source.box) { const b = source.box layer.ctx.drawImage(source.src, b.x, b.y, b.w, b.h, layer.x, layer.y, layer.w, layer.h) } else { layer.ctx.drawImage(source.src, layer.x, layer.y, layer.w, layer.h) } } layer.ctx.restore() } /** 按图层当前的源(原图 / 源画布 / 内容盒)与旋转角重绘该图层 */ export function redrawBitmapLayer(layer) { if (!layer || !layer.ctx) return layer.ctx.clearRect(0, 0, S.imgW, S.imgH) paintTransformed(layer, resolveSourceBox(layer)) } export function hitBitmapHandle(pos) { const layer = S.layers.find(l => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l))) if (!layer || layer.visible === false) return null const box = layerFrame(layer) if (!(box.w > 0 && box.h > 0)) return null const rot = layer.rotation || 0 const cx = box.x + box.w / 2, cy = box.y + box.h / 2 const lp = unrotPt(pos.x, pos.y, cx, cy, rot) const R = 14 / S.zoom if (hitRotationHandle(lp, box)) return 'rotate' const points = { nw: [box.x, box.y], ne: [box.x + box.w, box.y], sw: [box.x, box.y + box.h], se: [box.x + box.w, box.y + box.h], n: [box.x + box.w / 2, box.y], s: [box.x + box.w / 2, box.y + box.h], e: [box.x + box.w, box.y + box.h / 2], w: [box.x, box.y + box.h / 2] } let hit = null, best = Infinity for (const name in points) { const distance = Math.hypot(lp[0] - points[name][0], lp[1] - points[name][1]) if (distance < R && distance < best) { best = distance; hit = name } } return hit } // isDrawableLayer / restorePath / needsPixelSnapshot 统一由 shared/layer-logic.js 提供 // (快照端与恢复端必须共用同一判定,可单测守护) /** 内容包围盒(非透明像素范围),带缓存;step=2 降低扫描开销 */ function layerBounds(layer) { if (!layer || !layer.ctx || !layer.canvas) return null if (layer._bounds !== undefined) return layer._bounds let b = null try { const w = layer.canvas.width, h = layer.canvas.height const data = layer.ctx.getImageData(0, 0, w, h).data let minX = w, minY = h, maxX = -1, maxY = -1 for (let y = 0; y < h; y += 2) { for (let x = 0; x < w; x += 2) { if (data[(y * w + x) * 4 + 3] > 8) { if (x < minX) minX = x if (x > maxX) maxX = x if (y < minY) minY = y if (y > maxY) maxY = y } } } if (maxX >= 0) b = { x: minX, y: minY, w: maxX - minX + 2, h: maxY - minY + 2 } } catch (e) { b = null } layer._bounds = b return b } /** 控制框使用的范围:绘制类图层用内容盒,其余用图层矩形 */ function layerFrame(layer) { if (isDrawableLayer(layer) && !layer._srcBox) { const b = layerBounds(layer) if (b) return b } return { x: layer.x, y: layer.y, w: layer.w, h: layer.h } } /** 单个位图图层是否命中该点:绘制类按像素(透明处不算),图片类按矩形 */ export function hitBitmapAt(layer, pos) { if (!layer || layer.visible === false || layer.locked) return false const drawable = isDrawableLayer(layer) if (!drawable && !layer.transformable) return false if (!(layer.w > 0 && layer.h > 0)) return false const rot = layer.rotation || 0 const lp = rot ? unrotPt(pos.x, pos.y, layer.x + layer.w / 2, layer.y + layer.h / 2, rot) : [pos.x, pos.y] if (lp[0] < layer.x || lp[0] > layer.x + layer.w || lp[1] < layer.y || lp[1] > layer.y + layer.h) return false if (!drawable) return true const px = Math.round(lp[0]), py = Math.round(lp[1]) if (px < 0 || py < 0 || px >= layer.canvas.width || py >= layer.canvas.height) return false try { return layer.ctx.getImageData(px, py, 1, 1).data[3] > 8 } catch (e) { return true } } /** 兼容入口:按统一 z 降序找最上面的位图图层 */ export function hitBitmapLayer(pos) { for (const u of layerUnitsDesc()) { if (u.kind !== 'bitmap') continue if (hitBitmapAt(u.obj, pos)) return u.obj } return null } export function drawBitmapSelection(layer) { if (!layer) return // 变换框/手柄只在「选择」工具下出现(用户裁定 2026-11-04): // 画笔/橡皮等绘制工具下不显示调节杆,避免误抓手柄也减少视觉噪音。 if (S.tool !== 'select') return const drawable = isDrawableLayer(layer) if (!layer.transformable && !drawable) return const box = layerFrame(layer) if (!(box.w > 0 && box.h > 0)) return const ctx = S.overlayCtx const rot = layer.rotation || 0 const hs = 7 / S.zoom ctx.save() ctx.strokeStyle = '#e8a735' ctx.lineWidth = 1.5 / S.zoom ctx.setLineDash([6 / S.zoom, 3 / S.zoom]) const corners = boxCorners(box.x, box.y, box.w, box.h, rot) ctx.beginPath() ctx.moveTo(corners[0][0], corners[0][1]) for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1]) ctx.closePath() ctx.stroke() ctx.setLineDash([]) ctx.fillStyle = '#fff' ctx.strokeStyle = '#e8a735' const pts = frameHandlePoints(box, rot) for (const name in pts) { ctx.beginPath() ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2) ctx.fill(); ctx.stroke() } ctx.restore() drawRotationHandles(ctx, box, rot) } /** 任意矩形的 8 个控制点(含旋转)*/ function frameHandlePoints(box, rot) { const cx = box.x + box.w / 2, cy = box.y + box.h / 2 const local = { nw: [box.x, box.y], ne: [box.x + box.w, box.y], sw: [box.x, box.y + box.h], se: [box.x + box.w, box.y + box.h], n: [box.x + box.w / 2, box.y], s: [box.x + box.w / 2, box.y + box.h], e: [box.x + box.w, box.y + box.h / 2], w: [box.x, box.y + box.h / 2] } const out = {} for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot || 0) return out } export function beginBitmapDrag(handle, pos) { const layer = S.layers.find(l => l.id === S.selectedLayerId) if (!layer || layer.locked) return const drawable = isDrawableLayer(layer) if (!layer.transformable && !drawable) return if (drawable) { if (!layer.sourceCanvas) { const sc = document.createElement('canvas') sc.width = S.imgW; sc.height = S.imgH sc.getContext('2d').drawImage(layer.canvas, 0, 0) layer.sourceCanvas = sc } // 首次变换:记录内容盒作为源,并把图层矩形设为目标框 if (!layer._srcBox) { const b = layerBounds(layer) || { x: layer.x, y: layer.y, w: layer.w, h: layer.h } layer._srcBox = { x: b.x, y: b.y, w: b.w, h: b.h } layer.x = b.x; layer.y = b.y; layer.w = b.w; layer.h = b.h layer.rotation = layer.rotation || 0 } } const frame = layerFrame(layer) S.bitmapDrag = { mode: handle === 'rotate' ? 'rotate' : (handle ? 'scale' : 'move'), handle, start: pos, drawable: isDrawableLayer(layer), layer: { x: layer.x, y: layer.y, w: layer.w, h: layer.h, rotation: layer.rotation || 0 }, frame: { x: frame.x, y: frame.y, w: frame.w, h: frame.h }, pending: snapshotState() } } export function applyBitmapDrag(pos) { const drag = S.bitmapDrag const layer = S.layers.find(l => l.id === S.selectedLayerId) if (!drag || !layer) return const base = drag.layer if (drag.mode === 'move') { layer.x = base.x + pos.x - drag.start.x layer.y = base.y + pos.y - drag.start.y if (isDrawableLayer(layer)) layer._bounds = undefined } else if (drag.mode === 'rotate') { const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2 const a0 = Math.atan2(drag.start.y - rcy, drag.start.x - rcx) const a1 = Math.atan2(pos.y - rcy, pos.x - rcx) let deg = (base.rotation || 0) + (a1 - a0) * 180 / Math.PI if (S._shiftDown) deg = Math.round(deg / 15) * 15 layer.rotation = deg } else { const lpos = unrotPt(pos.x, pos.y, base.x + base.w / 2, base.y + base.h / 2, base.rotation || 0) let x = base.x, y = base.y, w = base.w, h = base.h const min = 4 if (drag.handle.includes('e')) w = Math.max(min, lpos[0] - base.x) if (drag.handle.includes('s')) h = Math.max(min, lpos[1] - base.y) if (drag.handle.includes('w')) { x = Math.min(lpos[0], base.x + base.w - min); w = base.x + base.w - x } if (drag.handle.includes('n')) { y = Math.min(lpos[1], base.y + base.h - min); h = base.y + base.h - y } if (S._shiftDown && layer.image) { const iw = layer.image.naturalWidth || layer.image.width const ih = layer.image.naturalHeight || layer.image.height const aspect = iw / Math.max(1, ih) if (w / h > aspect) h = w / aspect; else w = h * aspect if (drag.handle.includes('w')) x = base.x + base.w - w if (drag.handle.includes('n')) y = base.y + base.h - h } layer.x = x; layer.y = y; layer.w = w; layer.h = h } if (isDrawableLayer(layer)) layer._bounds = undefined redrawBitmapLayer(layer) } /** 切换画笔/橡皮作用的活动图层 */ export function setActiveLayer(id) { S.activeLayerId = id selectUnit('bitmap', id) renderLayerPanel() renderObjects() } /** 添加位图图层(导入图片)— 便利版:一步落层,不再需要 Enter 二次确认 * 需要调大小/位置时切换到「选择」工具拖动 8 个手柄;Ctrl+Z 可撤销这一步。 */ export function addBitmapLayer(img) { placeImageDirectly(img) } /** 确保有可绘制的活动图层:没有(或被锁定)就自动落一个「标注 N」空层并激活。 * 默认不再预建画笔层(用户裁定:需要时自己加),所以画笔起笔前必须兜底建层。 * 注意:本函数不进历史 —— 调用方(onBrushMouseDown)随后 saveSnapshot(), * 这样首笔 Ctrl+Z 会连「自动建的层 + 笔迹」一起撤掉,不留空层。 */ export function ensureWritableLayer() { const current = getActiveLayer() if (current && !current.locked) return current const id = S.layers.some(l => l.id === 'draw') ? 'L' + Date.now() + Math.floor(Math.random() * 1000) : 'draw' const canvas = createLayerCanvas() const ctx = canvas.getContext('2d', { willReadFrequently: true }) ctx.clearRect(0, 0, S.imgW, S.imgH) const layer = { id, name: '标注 ' + (S.layers.filter(l => l.id !== 'base').length + 1), canvas, ctx, opacity: 1, visible: true, locked: false, x: 0, y: 0, w: S.imgW, h: S.imgH, rotation: 0, z: ++S.zCounter } S.layers.push(layer) reorderLayerCanvas() // 新 canvas 必须立刻套上当前视图的显示尺寸/偏移,否则它会以原始像素尺寸 // 贴在 stack 原点 —— 表现就是「第一笔画在错误的位置,滚轮缩放后才正常」 // (addBlankLayer 一直有这步,这里漏了。2026-11-04 用户反馈) updateLayerCanvasStyles() setActiveLayer(id) renderLayerPanel() return layer } /** 新建空白图层 */ export function addBlankLayer() { // 创建可独立编辑的位图图层 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), canvas, ctx, opacity: 1, visible: true, locked: false, x: 0, y: 0, w: S.imgW, h: S.imgH, rotation: 0, z: ++S.zCounter } saveSnapshot() S.layers.push(layer) reorderLayerCanvas() setActiveLayer(id) updateLayerCanvasStyles() renderLayerPanel() } /** 删除图层(图层面板按钮与 Delete 快捷键共用) */ export function deleteLayer(id) { const idx = S.layers.findIndex(l => l.id === id) if (idx < 0) return // 不允许删除最后一个图层 if (S.layers.length <= 1) return const layer = S.layers[idx] if (layer.locked) return saveSnapshot() if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas) S.layers.splice(idx, 1) // 旧实现把位图 z 重设为 0..n-1,会与矢量对象的 z 再次撞车;统一重新分配 assignLayerZ(layerUnits()) // 如果删除的是活跃/选中图层,切到最后一个 if (S.activeLayerId === id) S.activeLayerId = S.layers[S.layers.length - 1].id if (S.selectedLayerId === id) S.selectedLayerId = null reorderLayerCanvas() renderLayerPanel() } // ============ 矢量对象独立画布(位图/矢量统一排序) ============ function vecCanvasFor(obj) { 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 c.height = S.imgH c.style.position = 'absolute' c.style.top = '0' c.style.left = '0' c.style.display = 'block' S.canvasStack.insertBefore(c, S.strokeCanvas) if (S.imgW && S.fitW) { const vw = Math.round(S.fitW * S.zoom) const vh = Math.round(S.fitH * S.zoom) const vs = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1 const vo = Math.round((S.overlayPad || 0) * vs) c.style.width = vw + 'px'; c.style.height = vh + 'px' c.style.left = vo + 'px'; c.style.top = vo + 'px' } obj._canvas = c obj._ctx = c.getContext('2d') } return obj } export function removeVecCanvas(obj) { if (obj && obj._canvas && obj._canvas.nodeType === 1) { if (obj._canvas.parentNode) obj._canvas.parentNode.removeChild(obj._canvas) obj._canvas = null obj._ctx = null } } export function purgeVectorCanvases() { for (const t of S.textLayers) removeVecCanvas(t) for (const sh of S.shapeLayers) removeVecCanvas(sh) } export function drawVectorToCanvas(kind, obj) { vecCanvasFor(obj) const ctx = obj._ctx ctx.clearRect(0, 0, S.imgW, S.imgH) if (kind === 'shape') { drawShape(ctx, obj) } else { ctx.save() ctx.textBaseline = 'top' ctx.globalAlpha = obj.opacity != null ? obj.opacity : 1 const rot = obj.rotation || 0 if (rot) { const b = textBounds(obj) const cx = b.x + b.w / 2, cy = b.y + b.h / 2 ctx.translate(cx, cy) ctx.rotate(rot * Math.PI / 180) ctx.translate(-cx, -cy) } ctx.font = TEXT_FONT(obj.fontSize) ctx.fillStyle = obj.color ctx.fillText(obj.text, obj.x, obj.y) ctx.restore() } } /** 切换图层可见性 */ function toggleLayerVisibility(id) { const layer = S.layers.find(l => l.id === id) if (!layer) return layer.visible = !layer.visible reorderLayerCanvas() renderLayerPanel() S.pickerComposite = null } /** 更新位图图层尺寸;位置始终由 canvas-stack 统一管理。 */ export function updateLayerCanvasStyles() { const w = Math.round(S.fitW * S.zoom) const h = Math.round(S.fitH * S.zoom) const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1 const offset = Math.round((S.overlayPad || 0) * scale) for (const layer of S.layers) { layer.canvas.style.width = w + 'px' layer.canvas.style.height = h + 'px' layer.canvas.style.left = offset + 'px' layer.canvas.style.top = offset + 'px' } styleVectorViewport(w, h, offset) } export function styleVectorViewport(w, h, offset) { for (const { obj } of allObjects()) { if (!obj._canvas) continue obj._canvas.style.width = w + 'px' obj._canvas.style.height = h + 'px' obj._canvas.style.left = offset + 'px' obj._canvas.style.top = offset + 'px' } } // ============ 图层面板 UI ============ export function renderLayerPanel() { const list = runtime.el.querySelector('.iwb-editor-layer-list') if (!list) return // 面板顺序直接取统一 z 序的倒序(与画布叠放完全一致)。 // 旧实现位图用 S.layers 数组序、矢量用 allObjects() 再 sort,z 相同时两者次序相反。 const items = [] for (const { kind, obj } of layerUnitsDesc()) { if (kind === 'bitmap') { items.push({ id: obj.id, type: 'bitmap', name: obj.name, opacity: obj.opacity, visible: obj.visible, z: obj.z, color: obj.color || S.color, lineWidth: obj.lineWidth || S.brushSize, // 高亮只代表「选中」;画笔作用目标独立用 ✎ 标记,避免两个图层同时亮 active: obj.id === S.selectedLayerId, paintTarget: obj.id === S.activeLayerId, locked: !!obj.locked, canDelete: S.layers.length > 1 }) } else { items.push({ id: obj.id, type: kind, name: kind === 'text' ? '"' + (obj.text || '').slice(0, 12) + '"' : (obj.type === 'rect' ? '矩形' : obj.type === 'circle' ? '圆形' : obj.type === 'pen' ? '钢笔形状' : '箭头'), opacity: obj.opacity != null ? obj.opacity : 1, visible: obj.visible !== false, z: obj.z || 0, color: obj.color || S.color, lineWidth: obj.lw || S.brushSize, active: (kind === 'text' && obj.id === S.selectedTextId) || (kind === 'shape' && obj.id === S.selectedShapeId), paintTarget: false, locked: !!obj.locked, canDelete: true }) } } let html = '' for (const item of items) { const activeClass = item.active ? ' active' : '' const visClass = item.visible ? '' : ' hidden' // SVG 图标 let typeIconSvg = '' if (item.type === 'bitmap') { typeIconSvg = '' } else if (item.type === 'text') { typeIconSvg = '' } else if (item.type === 'rect') { typeIconSvg = '' } else { typeIconSvg = '' } const visSvg = item.visible ? '' : '' const lockSvg = item.locked ? '' : '' const delSvg = '' html += `