上一次提交停在 1.2.12,本次把 1.3.0 → 1.6.0 四个版本的源码一并归档。 v1.3.0 色板进工具栏 + 矢量/文字工具只负责创建 - 工具栏最左色点 → 弹层(前调色器、后颜色设置 + 推荐颜色) - 弹层必须挂 .iwb-editor-modal 下:工具栏是 overflow-x:auto、画布 wrap 是 overflow:clip,塞进去会被裁 - applyColorChange 改 pointerdown 拍一次快照,修「拖调色器爆撤销栈」 - 每次按下前从 S.color 重同步 hsv,修「点推荐色后再拖 SV 跳回红」 - 外部点击改 document 捕获阶段监听(画布 mousedown preventDefault,冒泡收不到) - onShapeMouseDown / onTextMouseDown 不再命中已有对象;setTool 的 keepSel 只剩 select|picker v1.4.0 侧栏快速效果 - 6 个:反白(反相,非排版意义的黑底白字)/ 灰度 / 提亮 / 压暗 / 高对比 / 马赛克 - 目标是当前位图图层,标题右侧实时显示层名;不碰图层几何也不改 image - 导入图片层先克隆栅格化成「xxx · 效果」层、原层 visible=false(直接改像素会被 redraw 冲掉) - 撤销走快照,base 与画笔层走像素路径 v1.5.0 画完自动回 V,编辑统一走 V - 图形/文字落笔完成即退出当前工具并切 V - 钢笔改为只用 V 双击进节点编辑 - 双击判定改成自算 380ms 窗口:单击选中会重绘矢量画布,浏览器不再派发 dblclick v1.6.0 笔刷环 + 图层合并 - 画笔用 [ / ] 调粗细时立刻刷新笔刷环(原来只在 mousemove 里 drawToolRing,键改后不动) - 图层合并:⌘/Ctrl 点击多选后合并、⌘E 向下合并、⌘⇧E 合并可见(PS 语义) - 统一用 composeUnitsInto 合成并按结果重排 z,避免合并后像素为空 - 隐藏层不参与且保留;矢量(文字/形状/钢笔)直接栅格化 - 有 base 参与时写回 base(像素快照可逐像素撤销),否则新建位图层承载 harness 129 项全通。1.6.0 已发布到线上: plugin-image-annotate.198a20e4d722.js / sha256-GYog5NcinRDM67in67JxJUtBhUPB2lfttM/kw9UHwFo=
942 lines
41 KiB
JavaScript
942 lines
41 KiB
JavaScript
/* 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, refreshBrushRing } 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 = 5.5 / 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
|
||
|
||
// 先剔除已不存在的多选项(图层被删 / 已被合并),避免面板留着看不见的选择
|
||
if (S.layerMulti.length) {
|
||
const alive = new Set(layerUnits().map(u => u.kind + ':' + u.obj.id))
|
||
S.layerMulti = S.layerMulti.filter(r => alive.has(r.type + ':' + r.id))
|
||
}
|
||
|
||
// 面板顺序直接取统一 z 序的倒序(与画布叠放完全一致)。
|
||
// 旧实现位图用 S.layers 数组序、矢量用 allObjects() 再 sort,z 相同时两者次序相反。
|
||
const items = []
|
||
// 多选集合(⌘/Ctrl 点击累积):只影响「合并」目标,不抢单选高亮
|
||
const multiSet = new Set(S.layerMulti.map(x => x.type + ':' + x.id))
|
||
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,
|
||
multi: multiSet.has('bitmap:' + obj.id),
|
||
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),
|
||
multi: multiSet.has(kind + ':' + obj.id),
|
||
paintTarget: false, locked: !!obj.locked, canDelete: true
|
||
})
|
||
}
|
||
}
|
||
|
||
let html = ''
|
||
for (const item of items) {
|
||
const activeClass = item.active ? ' active' : ''
|
||
const multiClass = item.multi ? ' multi' : ''
|
||
const visClass = item.visible ? '' : ' hidden'
|
||
// SVG 图标
|
||
let typeIconSvg = ''
|
||
if (item.type === 'bitmap') {
|
||
typeIconSvg = '<svg width="13" height="13" 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"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>'
|
||
} else if (item.type === 'text') {
|
||
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 3 20 3 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="3" x2="12" y2="20"/></svg>'
|
||
} else if (item.type === 'rect') {
|
||
typeIconSvg = '<svg width="13" height="13" 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"/></svg>'
|
||
} else {
|
||
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>'
|
||
}
|
||
const visSvg = item.visible
|
||
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>'
|
||
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>'
|
||
const lockSvg = item.locked
|
||
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>'
|
||
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 7-2"/></svg>'
|
||
const delSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
|
||
html += `<div class="iwb-layer-item${activeClass}${multiClass}${visClass}" draggable="${item.id !== 'base'}" data-layer-id="${item.id}" data-layer-type="${item.type}">
|
||
<button class="iwb-layer-vis" data-vis-id="${item.id}" data-vis-type="${item.type}" title="${item.visible ? '隐藏' : '显示'}">${visSvg}</button>
|
||
<span class="iwb-layer-icon">${typeIconSvg}</span>
|
||
<span class="iwb-layer-name">${item.name}</span>${item.paintTarget ? '<span class="iwb-layer-paint" title="当前画笔 / 橡皮作用图层">✎</span>' : ''}
|
||
${(item.type === 'bitmap' || item.type === 'shape') ? `<input class="iwb-layer-color" type="color" value="${item.color}" data-color-id="${item.id}" data-color-type="${item.type}" title="调整颜色">` : ''}
|
||
${(item.type === 'bitmap' || item.type === 'shape') ? `<input class="iwb-layer-width" type="number" min="1" max="300" value="${Math.round(item.lineWidth)}" data-width-id="${item.id}" data-width-type="${item.type}" title="调整边框粗细">` : ''}
|
||
<button class="iwb-layer-lock${item.locked ? ' active' : ''}" data-lock-id="${item.id}" data-lock-type="${item.type}" title="${item.locked ? '解锁图层' : '锁定图层'}">${lockSvg}</button>
|
||
${item.canDelete ? `<button class="iwb-layer-del" data-del-id="${item.id}" data-del-type="${item.type}" title="删除图层">${delSvg}</button>` : ''}
|
||
</div>`
|
||
}
|
||
list.innerHTML = html
|
||
|
||
// 侧栏「快速效果」的目标层名:效果和画笔共用同一个目标层,这里一起刷,
|
||
// 免得切层后标签还停在上一个图层名上。
|
||
const fxTarget = runtime.el.querySelector('.iwb-editor-fx-target')
|
||
if (fxTarget) {
|
||
const active = getActiveLayer()
|
||
fxTarget.textContent = active ? active.name : '无图层'
|
||
fxTarget.title = active
|
||
? '效果作用于当前位图图层:' + active.name + '(切换图层可改变目标)'
|
||
: '当前没有可处理的位图图层'
|
||
}
|
||
|
||
// 绑定图层面板事件
|
||
bindLayerPanelEvents()
|
||
}
|
||
|
||
function reorderPanelItem(dragId, targetId) {
|
||
if (!dragId || !targetId || dragId === targetId || dragId === 'base' || targetId === 'base') return
|
||
const all = layerUnits()
|
||
const baseIdx = all.findIndex(u => u.obj.id === 'base')
|
||
if (baseIdx > 0) { const [b] = all.splice(baseIdx, 1); all.unshift(b) }
|
||
const from = all.findIndex(item => item.obj.id === dragId)
|
||
const to0 = all.findIndex(item => item.obj.id === targetId)
|
||
if (from < 0 || to0 < 0) return
|
||
const before = all.map(u => u.obj.id).join('|')
|
||
const [moved] = all.splice(from, 1)
|
||
const to = Math.max(all.findIndex(item => item.obj.id === targetId), baseIdx >= 0 ? 1 : 0)
|
||
all.splice(to, 0, moved)
|
||
if (all.map(u => u.obj.id).join('|') === before) return
|
||
saveSnapshot()
|
||
assignLayerZ(all)
|
||
reorderLayerCanvas()
|
||
sortLayersByZ()
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
|
||
function bindLayerPanelEvents() {
|
||
const list = runtime.el.querySelector('.iwb-editor-layer-list')
|
||
if (!list) return
|
||
|
||
bindLayerItemEvents(list)
|
||
bindLayerStyleInputs(list)
|
||
bindLayerVisButtons(list)
|
||
bindLayerLockButtons(list)
|
||
bindLayerDelButtons(list)
|
||
}
|
||
|
||
/** 图层面板项:点击选中(位图/文字/形状)+ 拖到另一项上排序 */
|
||
function bindLayerItemEvents(list) {
|
||
// 点击图层项 → 设为活跃
|
||
list.querySelectorAll('.iwb-layer-item').forEach(item => {
|
||
item.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
item.addEventListener('dragstart', (e) => { if (item.draggable) { e.dataTransfer.setData('text/plain', item.dataset.layerId); item.classList.add('dragging') } })
|
||
item.addEventListener('dragend', () => item.classList.remove('dragging'))
|
||
item.addEventListener('dragover', (e) => { if (item.draggable) e.preventDefault() })
|
||
item.addEventListener('drop', (e) => { e.preventDefault(); reorderPanelItem(e.dataTransfer.getData('text/plain'), item.dataset.layerId) })
|
||
item.addEventListener('click', (e) => {
|
||
if (e.target.closest('.iwb-layer-vis') || e.target.closest('.iwb-layer-lock') || e.target.closest('.iwb-layer-del')) return
|
||
const id = item.dataset.layerId
|
||
const type = item.dataset.layerType
|
||
// ⌘/Ctrl 点击:加入/移出合并集合(不改变画笔目标与单选高亮)
|
||
if (e.metaKey || e.ctrlKey) {
|
||
e.preventDefault()
|
||
toggleLayerMulti(type, id)
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
// 普通点击回到单选语义:先把合并集合清掉,避免留下看不见的选择
|
||
if (S.layerMulti.length) S.layerMulti.length = 0
|
||
if (type === 'bitmap') {
|
||
setActiveLayer(id)
|
||
} else if (type === 'text' || type === 'shape') {
|
||
selectUnit(type, id)
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
/** 图层颜色与边框粗细输入:修改后立即刷新画布和面板 */
|
||
function bindLayerStyleInputs(list) {
|
||
// 图层颜色与边框粗细:修改后立即刷新画布和面板。
|
||
list.querySelectorAll('.iwb-layer-color').forEach(input => {
|
||
input.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
input.addEventListener('input', (e) => {
|
||
e.stopPropagation()
|
||
const id = input.dataset.colorId
|
||
const type = input.dataset.colorType
|
||
const obj = type === 'bitmap' ? S.layers.find(l => l.id === id) : S.shapeLayers.find(s => s.id === id)
|
||
if (obj) { obj.color = input.value; S.color = input.value; updateColorUI(); renderObjects(); renderLayerPanel(); S.pickerComposite = null }
|
||
})
|
||
})
|
||
list.querySelectorAll('.iwb-layer-width').forEach(input => {
|
||
input.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
input.addEventListener('input', (e) => {
|
||
e.stopPropagation()
|
||
const id = input.dataset.widthId
|
||
const type = input.dataset.widthType
|
||
const value = clamp(parseInt(input.value, 10) || 1, 1, 300)
|
||
const obj = type === 'bitmap' ? S.layers.find(l => l.id === id) : S.shapeLayers.find(s => s.id === id)
|
||
if (obj) { obj.lineWidth = value; if (type === 'shape') obj.lw = value; else { S.brushSize = value; refreshBrushRing() } renderObjects(); updateBrushParamUI(); renderLayerPanel() }
|
||
})
|
||
})
|
||
}
|
||
|
||
/** 显隐切换按钮:位图直接切 visible,文字/形状切对象 visible 并重绘 */
|
||
function bindLayerVisButtons(list) {
|
||
// 显隐切换
|
||
list.querySelectorAll('.iwb-layer-vis').forEach(btn => {
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', (e) => {
|
||
e.stopPropagation()
|
||
const id = btn.dataset.visId
|
||
const type = btn.dataset.visType
|
||
if (type === 'bitmap') {
|
||
toggleLayerVisibility(id)
|
||
} else if (type === 'text') {
|
||
const obj = S.textLayers.find(t => t.id === id)
|
||
if (obj) { obj.visible = obj.visible === false; renderObjects(); renderLayerPanel(); S.pickerComposite = null }
|
||
} else if (type === 'shape') {
|
||
const obj = S.shapeLayers.find(s => s.id === id)
|
||
if (obj) { obj.visible = obj.visible === false; renderObjects(); renderLayerPanel(); S.pickerComposite = null }
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
/** 锁定/解锁按钮:切换对象 locked 并存快照 */
|
||
function bindLayerLockButtons(list) {
|
||
// 锁定/解锁
|
||
list.querySelectorAll('.iwb-layer-lock').forEach(btn => {
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', (e) => {
|
||
e.stopPropagation()
|
||
const id = btn.dataset.lockId
|
||
const type = btn.dataset.lockType
|
||
const obj = type === 'bitmap' ? S.layers.find(l => l.id === id) : type === 'text' ? S.textLayers.find(t => t.id === id) : S.shapeLayers.find(s => s.id === id)
|
||
if (!obj) return
|
||
saveSnapshot()
|
||
obj.locked = !obj.locked
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
})
|
||
})
|
||
}
|
||
|
||
/** 删除按钮:按类型删除位图图层 / 文字 / 形状 */
|
||
function bindLayerDelButtons(list) {
|
||
// 删除图层
|
||
list.querySelectorAll('.iwb-layer-del').forEach(btn => {
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', (e) => {
|
||
e.stopPropagation()
|
||
const id = btn.dataset.delId
|
||
const type = btn.dataset.delType
|
||
if (type === 'bitmap') {
|
||
deleteLayer(id)
|
||
} else if (type === 'text') {
|
||
S.selectedTextId = id
|
||
deleteSelectedText()
|
||
renderLayerPanel()
|
||
} else if (type === 'shape') {
|
||
S.selectedShapeId = id
|
||
deleteSelectedShape()
|
||
renderLayerPanel()
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
// ============ 图层合并(v1.6,用户裁定) ============
|
||
|
||
const multiKey = (type, id) => type + ':' + id
|
||
|
||
/** 当前单选的是哪个单元(多选的起点);没有选中返回 null */
|
||
function currentUnitRef() {
|
||
if (S.selectedLayerId) return { type: 'bitmap', id: S.selectedLayerId }
|
||
if (S.selectedTextId) return { type: 'text', id: S.selectedTextId }
|
||
if (S.selectedShapeId) return { type: 'shape', id: S.selectedShapeId }
|
||
return null
|
||
}
|
||
|
||
/** ⌘/Ctrl 点击图层项:加入或移出「合并集合」。
|
||
* 第一次加选时把当前单选层一起纳入,符合「先选一层再按住 ⌘ 加选」的习惯。 */
|
||
export function toggleLayerMulti(type, id) {
|
||
const key = multiKey(type, id)
|
||
const i = S.layerMulti.findIndex(x => multiKey(x.type, x.id) === key)
|
||
if (i >= 0) { S.layerMulti.splice(i, 1); return }
|
||
if (!S.layerMulti.length) {
|
||
const cur = currentUnitRef()
|
||
if (cur && multiKey(cur.type, cur.id) !== key) S.layerMulti.push(cur)
|
||
}
|
||
S.layerMulti.push({ type, id })
|
||
}
|
||
|
||
export function clearLayerMulti() { S.layerMulti.length = 0 }
|
||
|
||
/** 把一组单元按 z 从低到高叠进目标位图层的像素。
|
||
* alpha 规则与 getCompositeCanvas(导出/吸管)保持一致,保证「合并后看到的就是导出结果」。 */
|
||
function composeUnitsInto(layer, units) {
|
||
const tmp = document.createElement('canvas')
|
||
tmp.width = S.imgW
|
||
tmp.height = S.imgH
|
||
const tctx = tmp.getContext('2d')
|
||
for (const u of units) {
|
||
const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas
|
||
if (!el || el.nodeType !== 1) continue
|
||
tctx.globalAlpha = u.obj.opacity == null ? 1 : u.obj.opacity
|
||
tctx.drawImage(el, 0, 0)
|
||
}
|
||
tctx.globalAlpha = 1
|
||
// 图层 ctx 平时带视图变换,写像素必须回到设备坐标;copy 一并覆盖透明区域
|
||
const ctx = layer.ctx
|
||
ctx.save()
|
||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||
ctx.globalAlpha = 1
|
||
ctx.globalCompositeOperation = 'copy'
|
||
ctx.filter = 'none'
|
||
ctx.drawImage(tmp, 0, 0)
|
||
ctx.restore()
|
||
}
|
||
|
||
/** 删除一个图层单元:位图连 DOM 画布一起释放,矢量移除自己的画布 */
|
||
function dropUnit(u) {
|
||
if (u.kind === 'bitmap') {
|
||
const i = S.layers.indexOf(u.obj)
|
||
if (i >= 0) S.layers.splice(i, 1)
|
||
try {
|
||
if (u.obj.canvas && u.obj.canvas.parentNode) u.obj.canvas.parentNode.removeChild(u.obj.canvas)
|
||
} catch (e) { /* 单个图层释放失败不阻断合并 */ }
|
||
} else if (u.kind === 'text') {
|
||
S.textLayers = S.textLayers.filter(t => t !== u.obj)
|
||
removeVecCanvas(u.obj)
|
||
} else if (u.kind === 'shape') {
|
||
S.shapeLayers = S.shapeLayers.filter(s => s !== u.obj)
|
||
removeVecCanvas(u.obj)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 把若干单元合成一张位图,并删掉参与合并的单元。
|
||
*
|
||
* 有「原图(base)」参与时写回 base 本身:base 的快照走 pixels 路径,撤销能原样恢复,
|
||
* 而且「还原原图」永远有锚点可回。其余情况新建一张普通位图承载 —— 导入图片层走
|
||
* image 重绘路径,如果原地改像素再清掉 image,撤销时 history 的 restorePath 会按
|
||
* 「像素」去读一份根本没拍的快照(详见 history.js 的注释),像素就丢了。
|
||
*/
|
||
function mergeUnits(units) {
|
||
const sorted = units.slice().sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
|
||
const lowUnit = sorted[0]
|
||
const baseUnit = sorted.find(u => u.kind === 'bitmap' && u.obj.id === 'base')
|
||
// 结果层要落回「原最低层」的位置:先数清它下面还有几个不参与合并的层
|
||
const all = layerUnits()
|
||
const lowIdx = all.findIndex(u => u.obj === lowUnit.obj)
|
||
const chosenSet = new Set(sorted.map(u => u.obj))
|
||
const insertAt = all.slice(0, Math.max(lowIdx, 0)).filter(u => !chosenSet.has(u.obj)).length
|
||
|
||
let carrier
|
||
if (baseUnit) {
|
||
carrier = baseUnit.obj
|
||
// 合并后它就是纯像素层:断掉 image/sourceCanvas,避免后续按原图重新重绘
|
||
carrier.image = null
|
||
carrier.sourceCanvas = null
|
||
carrier._srcBox = null
|
||
carrier.transformable = false
|
||
carrier.x = 0
|
||
carrier.y = 0
|
||
carrier.w = S.imgW
|
||
carrier.h = S.imgH
|
||
carrier.rotation = 0
|
||
carrier.visible = true
|
||
carrier.opacity = 1
|
||
carrier._bounds = undefined
|
||
composeUnitsInto(carrier, sorted)
|
||
for (const u of sorted) if (u.obj !== carrier) dropUnit(u)
|
||
// base 永远压在最底,其余层保持原有相对顺序
|
||
const rest = layerUnits().filter(u => u.obj !== carrier)
|
||
rest.unshift({ kind: 'bitmap', obj: carrier })
|
||
assignLayerZ(rest)
|
||
} else {
|
||
const canvas = createLayerCanvas()
|
||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||
carrier = {
|
||
id: 'm' + Date.now() + Math.floor(Math.random() * 1000),
|
||
name: lowUnit.obj.name || '合并图层',
|
||
canvas,
|
||
ctx,
|
||
opacity: 1,
|
||
visible: true,
|
||
locked: false,
|
||
x: 0, y: 0, w: S.imgW, h: S.imgH,
|
||
rotation: 0,
|
||
z: lowUnit.obj.z || 0
|
||
}
|
||
composeUnitsInto(carrier, sorted)
|
||
for (const u of sorted) dropUnit(u)
|
||
S.layers.push(carrier)
|
||
// carrier 已在 layerUnits() 里,先排掉再按原最低层的位置插回去 —— 否则同一个对象会被计两次 z
|
||
const rest = layerUnits().filter(u => u.obj !== carrier)
|
||
rest.splice(Math.min(insertAt, rest.length), 0, { kind: 'bitmap', obj: carrier })
|
||
assignLayerZ(rest)
|
||
}
|
||
|
||
S.activeLayerId = carrier.id
|
||
S.selectedLayerId = carrier.id
|
||
S.selectedTextId = null
|
||
S.selectedShapeId = null
|
||
S.textDrag = null
|
||
S.shapeDrag = null
|
||
S.bitmapDrag = null
|
||
S.layerMulti.length = 0
|
||
S.pickerComposite = null
|
||
sortLayersByZ()
|
||
reorderLayerCanvas()
|
||
updateLayerCanvasStyles()
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
if (S.renderAll) S.renderAll()
|
||
return carrier
|
||
}
|
||
|
||
/**
|
||
* 合并图层(Ctrl/⌘+E)
|
||
* - 图层列表里有 2 个以上多选(⌘/Ctrl 点击)→ 合并这些图层
|
||
* - 否则 → 「向下合并」:当前层合进下面一层,结果继承下层名字与位置
|
||
* 隐藏层不参与合并、原样保留(看不见的内容不该被烘进结果)。
|
||
*/
|
||
export function mergeLayers() {
|
||
const units = layerUnits()
|
||
if (units.length < 2) return { ok: false, msg: '只有一个图层,没有可合并的对象' }
|
||
|
||
let chosen
|
||
if (S.layerMulti.length >= 2) {
|
||
chosen = units.filter(u => S.layerMulti.some(r => r.type === u.kind && r.id === u.obj.id))
|
||
if (chosen.length < 2) return { ok: false, msg: '先选两个以上图层(⌘/Ctrl 点击图层列表)' }
|
||
} else {
|
||
const cur = currentUnitRef()
|
||
const idx = cur ? units.findIndex(u => u.kind === cur.type && u.obj.id === cur.id) : -1
|
||
if (idx < 0) return { ok: false, msg: '先在图层列表里选中一层' }
|
||
if (idx === 0) return { ok: false, msg: '已经是最底层,没有可合并的下一层' }
|
||
chosen = [units[idx - 1], units[idx]]
|
||
if (chosen[1].obj.visible === false) return { ok: false, msg: '当前层已隐藏,先显示再合并' }
|
||
if (chosen[0].obj.visible === false) return { ok: false, msg: '下一层已隐藏,先显示再合并' }
|
||
}
|
||
|
||
const visible = chosen.filter(u => u.obj.visible !== false)
|
||
if (visible.length < 2) return { ok: false, msg: '可见图层不足 2 个,没有可合并的内容' }
|
||
|
||
saveSnapshot('合并图层')
|
||
mergeUnits(visible)
|
||
return { ok: true, msg: '已合并 ' + visible.length + ' 个图层 · Ctrl+Z 撤销' }
|
||
}
|
||
|
||
/** 合并可见图层(Ctrl/⌘+Shift+E):隐藏层保留不动 */
|
||
export function mergeVisibleLayers() {
|
||
const visible = layerUnits().filter(u => u.obj.visible !== false)
|
||
if (visible.length < 2) return { ok: false, msg: '可见图层不足 2 个,没有可合并的对象' }
|
||
saveSnapshot('合并可见图层')
|
||
mergeUnits(visible)
|
||
return { ok: true, msg: '已合并 ' + visible.length + ' 个可见图层 · Ctrl+Z 撤销' }
|
||
}
|