/* crop.js - 裁剪工具 * 节:裁剪、裁剪栏。 * 遮罩绘制写 S.overlayCanvas;确认裁剪后逐图层搬运像素(v1.2 起不再 flatten)。 */ 'use strict' import { S, runtime } from './state.js' import { resizeWorkspace } from './viewport.js' import { resetOverlayTransform, viewScale } from './scale.js' import { disposeSelection } from './selection.js' import { saveSnapshot } from './history.js' import { toast } from './commands.js' // ============ 裁剪 ============ // parseRatio 由 shared/image-math.js 提供(可单测) /** 设置裁剪约束 */ export function setConstraint(type, ratio, sizeW, sizeH) { S.cropConstraint = { type, ratio: ratio || 0, sizeW: sizeW || 0, sizeH: sizeH || 0 } const toggle = runtime.el && runtime.el.querySelector('.iwb-editor-size-toggle') if (toggle) { const active = type === 'size' toggle.classList.toggle('active', active) toggle.setAttribute('aria-pressed', String(active)) toggle.textContent = active ? '已启用' : '启用尺寸' } if (S.cropRect) { S.cropRect = applyConstraint(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h) drawCropPreview() updateCropInfo() } } function applyConstraint(x, y, w, h) { const c = S.cropConstraint if (c.type === 'free' || !c.ratio || c.ratio <= 0) return { x, y, w, h } const ratio = c.ratio if (w / h > ratio) { const nw = h * ratio const dx = (w - nw) / 2 return { x: x + dx, y, w: nw, h } } else { const nh = w / ratio const dy = (h - nh) / 2 return { x, y: y + dy, w, h: nh } } } export function applyConstraintDrag(x1, y1, x2, y2) { const c = S.cropConstraint let rx = Math.min(x1, x2), ry = Math.min(y1, y2) let rw = Math.abs(x2 - x1), rh = Math.abs(y2 - y1) if (rw < 1) rw = 1 if (rh < 1) rh = 1 if (c.type === 'free' || !c.ratio || c.ratio <= 0) return { x: rx, y: ry, w: rw, h: rh } const ratio = c.ratio if (rw / rh > ratio) { rh = rw / ratio } else { rw = rh * ratio } return { x: rx, y: ry, w: rw, h: rh } } export function updateCropInfo() { const info = runtime.el.querySelector('.iwb-editor-crop-info') if (!info) return if (S.cropRect) { const w = Math.round(S.cropRect.w) const h = Math.round(S.cropRect.h) const c = S.cropConstraint if (c.type === 'size' && c.sizeW > 0 && c.sizeH > 0) { info.textContent = `${w}x${h} -> ${c.sizeW}x${c.sizeH}` } else { info.textContent = `${w}x${h}` } } else { info.textContent = '--' } } export function clearOverlay() { const ctx = S.overlayCtx if (!ctx) return // 缓冲已按 overlayScale 放大,必须按设备像素整幅清,再恢复图片坐标基准 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 drawCropPreview(x1, y1, x2, y2) { const ctx = S.overlayCtx clearOverlay() let rx, ry, rw, rh if (x2 !== undefined) { const r = applyConstraintDrag(x1, y1, x2, y2) rx = r.x; ry = r.y; rw = r.w; rh = r.h } else if (S.cropRect) { rx = S.cropRect.x; ry = S.cropRect.y rw = S.cropRect.w; rh = S.cropRect.h } else { return } ctx.save() ctx.fillStyle = 'rgba(0,0,0,0.45)' const cropPad = Math.max(S.imgW, S.imgH) * 2 ctx.fillRect(-cropPad, -cropPad, S.imgW + cropPad * 2, S.imgH + cropPad * 2) ctx.globalCompositeOperation = 'destination-out' ctx.fillRect(rx, ry, rw, rh) ctx.restore() ctx.save() ctx.strokeStyle = '#4488ff' ctx.lineWidth = 2 / viewScale() ctx.setLineDash([8 / viewScale(), 4 / viewScale()]) ctx.strokeRect(rx, ry, rw, rh) ctx.restore() if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh) } function cropHandlePoints(rx, ry, rw, rh) { return { nw: [rx, ry], ne: [rx + rw, ry], sw: [rx, ry + rh], se: [rx + rw, ry + rh], n: [rx + rw / 2, ry], s: [rx + rw / 2, ry + rh], e: [rx + rw, ry + rh / 2], w: [rx, ry + rh / 2] } } function drawCropHandles(rx, ry, rw, rh) { const ctx = S.overlayCtx const pts = cropHandlePoints(rx, ry, rw, rh) const hs = 4 / viewScale() ctx.save() ctx.fillStyle = '#ffffff' ctx.strokeStyle = '#4488ff' ctx.lineWidth = 1.5 / viewScale() 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() } export function insideRect(pos, rect) { return pos.x >= rect.x && pos.x <= rect.x + rect.w && pos.y >= rect.y && pos.y <= rect.y + rect.h } export function hitCropHandle(pos) { if (!S.cropRect) return null const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h) const R = 12 / viewScale() let best = null, bestDist = 1e9 for (const name in pts) { const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1] const d = dx * dx + dy * dy if (d < R * R && d < bestDist) { bestDist = d; best = name } } return best } export function resizeCropRect(pos) { if (!S.cropRect) return const { x, y, w, h } = S.cropRect const c = S.cropConstraint let nx = x, ny = y, nw = w, nh = h const hh = S.cropHandle // 自由比例:允许超出画布边界(负值/超出值都合法),只限制最小尺寸 if (c.type === 'free' || !c.ratio || c.ratio <= 0) { if (hh.includes('e')) nw = Math.max(4, pos.x - x) if (hh.includes('s')) nh = Math.max(4, pos.y - y) if (hh.includes('w')) { const right = x + w; nx = Math.min(pos.x, right - 4); nw = right - nx } if (hh.includes('n')) { const bottom = y + h; ny = Math.min(pos.y, bottom - 4); nh = bottom - ny } S.cropRect = { x: nx, y: ny, w: nw, h: nh } return } // 等比约束:同样允许超出画布边界 const ratio = c.ratio if (hh === 'e' || hh === 'w') { if (hh === 'e') { nw = Math.max(4, pos.x - x) } else { const right = x + w nx = Math.min(pos.x, right - 4) nw = right - nx } nh = nw / ratio } else if (hh === 'n' || hh === 's') { if (hh === 's') { nh = Math.max(4, pos.y - y) } else { const bottom = y + h ny = Math.min(pos.y, bottom - 4) nh = bottom - ny } nw = nh * ratio } else { if (hh === 'se') { nw = Math.max(4, pos.x - x) nh = Math.max(4, pos.y - y) } else if (hh === 'ne') { nw = Math.max(4, pos.x - x) const bottom = y + h ny = Math.min(pos.y, bottom - 4) nh = bottom - ny } else if (hh === 'sw') { const right = x + w nx = Math.min(pos.x, right - 4) nw = right - nx nh = Math.max(4, pos.y - y) } else if (hh === 'nw') { const right = x + w nx = Math.min(pos.x, right - 4) nw = right - nx const bottom = y + h ny = Math.min(pos.y, bottom - 4) nh = bottom - ny } // 等比修正 if (nw / nh > ratio) { nh = nw / ratio if (hh === 'ne' || hh === 'nw') ny = y + h - nh } else { nw = nh * ratio if (hh === 'nw' || hh === 'sw') nx = x + w - nw } } S.cropRect = { x: nx, y: ny, w: nw, h: nh } } /** * 确认裁剪(v1.2 起非破坏性:可撤销、不 flatten)。 * * 旧实现把可见图层合成成一张图再 setupCanvas,等于:① 所有图层被合并成一张; * ② S.history 直接清零 —— 裁错了没有任何退路。现在改为: * ① 先 saveSnapshot('裁剪'),快照记的是「裁剪前」的尺寸 + 每层像素; * ② 逐图层把可见区域搬进新尺寸的 canvas(图层结构、命名、透明度、锁定全保留); * ③ resizeWorkspace 只换尺寸不重建图层,像素随后写回。 * 撤销时 restoreState 会先把画布尺寸复位到快照里的 imgW/imgH,再回填像素。 */ export function confirmCrop() { if (!S.cropRect) return const { x, y, w, h } = S.cropRect if (w < 2 || h < 2) { cancelCrop(); return } const c = S.cropConstraint const sx = Math.round(x), sy = Math.round(y) const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h)) const isSize = c.type === 'size' && c.sizeW > 0 && c.sizeH > 0 const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh // 完全没变就别记一步空历史 if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) { cancelCrop(); return } const oldW = S.imgW, oldH = S.imgH const scaleX = nw / sw, scaleY = nh / sh // 裁剪框可以超出画面:源矩形先夹到画面内,目标矩形按同一比例落位(超出部分为透明) const srcX = Math.max(0, sx), srcY = Math.max(0, sy) const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX) const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY) const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY const dstW = srcW * scaleX, dstH = srcH * scaleY // ① 进历史:快照记「裁剪前」的尺寸与每层像素 saveSnapshot('裁剪') // ② 旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效 disposeSelection() // ③ 逐图层把可见区域搬出来(保留图层结构,不再合成成一张) const staged = S.layers.map(layer => { const tmp = document.createElement('canvas') tmp.width = nw tmp.height = nh if (srcW > 0 && srcH > 0) { try { tmp.getContext('2d').drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH) } catch (e) { /* 单层搬运失败不阻断其余 */ } } return tmp }) // ④ 换尺寸(会清空图层像素)后把搬出来的内容写回 resizeWorkspace(nw, nh) S.layers.forEach((layer, i) => { const tmp = staged[i] try { layer.ctx.drawImage(tmp, 0, 0) } catch (e) { /* ignore */ } tmp.width = 0 tmp.height = 0 // 像素已落在新坐标系的正确位置,几何元数据不能再参与二次定位; // 图片源(image / sourceCanvas)尺寸是旧的,留着会让重绘错位,必须摘掉。 // 摘掉后这些层按「像素层」参与快照与恢复(见 vendor/layer-logic.js)。 layer.x = 0 layer.y = 0 layer.w = nw layer.h = nh layer.rotation = 0 layer.transformable = false layer.image = null layer.sourceCanvas = null layer._srcBox = null layer._bounds = undefined }) // ⑤ 文字/形状按裁剪区域位移与缩放 S.textLayers = S.textLayers.map(t => ({ ...t, x: (t.x - sx) * scaleX, y: (t.y - sy) * scaleY, fontSize: t.fontSize * scaleX })) S.shapeLayers = S.shapeLayers.map(s => ({ ...s, ...(s.type === 'pen' ? { pts: (s.pts || []).map(p => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : { x1: (s.x1 - sx) * scaleX, y1: (s.y1 - sy) * scaleY, x2: (s.x2 - sx) * scaleX, y2: (s.y2 - sy) * scaleY }), lw: Math.max(1, s.lw * (scaleX + scaleY) / 2) })) S.selectedTextId = null S.textDrag = null S.selectedShapeId = null S.shapeDrag = null // 裁剪后图层 id 不变但几何全变,旧的选中 id 与拖拽中间态都要清 S.selectedLayerId = null S.bitmapDrag = null S.zoom = 1 S.cropRect = null S.cropHandle = null S.cropMoving = false S.moveStart = null updateCropInfo() if (S.renderAll) S.renderAll() toast('已裁剪为 ' + nw + '×' + nh + '(Ctrl+Z 可撤销)', 'success') } export function cancelCrop() { S.cropRect = null S.cropHandle = null S.cropMoving = false S.moveStart = null clearOverlay() updateCropInfo() } // ============ 裁剪栏 ============ // 裁剪参数已迁入选项栏(optionBarHTML('crop'),随工具切换自动出现/消失), // 画布下方的浮窗 DOM 已删除。这两个入口保留为空操作,调用点(setTool / 拉框)无需改动。 export function showCropBar() { /* 选项栏自动承载,见 events.js#optionBarHTML */ } export function hideCropBar() { /* 同上 */ }