/* tools.js - 画笔、橡皮、吸管与合成画布 * 节:绘制工具、合成画布(吸管取样 / 导出 / 裁剪共用)。 * 约定:brushStampCache 是模块级缓存,只在本模块内重建; * getCompositeCanvas 把所有可见图层+矢量对象合成到一张画布, * 吸管/导出/裁剪共用它。 */ 'use strict' import { S, runtime } from './state.js' import { commitTextInput, getSelectedShape, getSelectedText, layerUnits, renderObjects, shapeBounds } from './objects.js' import { cancelCrop, clearOverlay, hideCropBar, showCropBar, updateCropInfo } from './crop.js' import { cancelImagePlacement } from './placement.js' import { clamp } from './viewport.js' import { resetOverlayTransform } from './scale.js' import { getActiveCtx, getActiveLayer, renderLayerPanel } from './layers.js' import { saveSnapshot } from './history.js' import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js' import { isDrawableLayer } from '../vendor/layer-logic.js' import { hexToRgb, rgbToHex } from '../vendor/image-math.js' import { rememberColor } from './recent-colors.js' // ============ 绘制工具 ============ // hexToRgb / rgbToHex / parseRatio 统一由 shared/image-math.js 提供(可单测) let brushStampCache = { key: '', canvas: null } /** 软边笔刷章:径向渐变离屏 canvas */ function getBrushStamp(size, color, hardness) { const key = size + '|' + color + '|' + hardness if (brushStampCache.key === key && brushStampCache.canvas) return brushStampCache.canvas const c = document.createElement('canvas') c.width = size c.height = size const cx = c.getContext('2d') const half = size / 2 const { r, g, b } = hexToRgb(color) const grad = cx.createRadialGradient(half, half, half * hardness / 100, half, half, half) grad.addColorStop(0, `rgba(${r},${g},${b},1)`) grad.addColorStop(1, `rgba(${r},${g},${b},0)`) cx.fillStyle = grad cx.fillRect(0, 0, size, size) brushStampCache = { key, canvas: c } return c } /** 画笔/橡皮一笔的一段:画在 strokeCanvas(全不透明),透明度由 endStroke 合成时承担 * 橡皮用白色(destination-out 合成时只取 alpha 通道) */ export function strokeSegment(x1, y1, x2, y2) { const ctx = S.strokeCtx const size = Math.max(1, S.brushSize) const color = S.tool === 'eraser' ? '#ffffff' : S.color ctx.save() if (S.brushHardness >= 100) { ctx.strokeStyle = color ctx.lineWidth = size ctx.lineCap = 'round' ctx.lineJoin = 'round' ctx.beginPath() ctx.moveTo(x1, y1) ctx.lineTo(x2, y2) ctx.stroke() } else { const stamp = getBrushStamp(size, color, S.brushHardness) const dist = Math.hypot(x2 - x1, y2 - y1) const step = Math.max(1, size / 6) const n = Math.max(0, Math.ceil(dist / step)) for (let i = 0; i <= n; i++) { const t = n === 0 ? 0 : i / n ctx.drawImage(stamp, x1 + (x2 - x1) * t - size / 2, y1 + (y2 - y1) * t - size / 2) } } ctx.restore() S.strokeCanvas.style.opacity = S.brushOpacity } export function eraseSegment(x1, y1, x2, y2) { const ctx = getActiveCtx() if (!ctx) return ctx.save() if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule) ctx.globalCompositeOperation = 'destination-out' ctx.globalAlpha = S.brushOpacity ctx.lineWidth = Math.max(1, S.brushSize) ctx.lineCap = 'round' ctx.lineJoin = 'round' ctx.beginPath() ctx.moveTo(x1, y1) ctx.lineTo(x2, y2) ctx.stroke() ctx.restore() const active = getActiveLayer() if (active && active.id === 'draw' && active.sourceCanvas) { const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true }) sourceCtx.save() sourceCtx.globalCompositeOperation = 'destination-out' sourceCtx.globalAlpha = S.brushOpacity sourceCtx.lineWidth = Math.max(1, S.brushSize) * active.w / Math.max(S.imgW, 1) sourceCtx.lineCap = 'round' sourceCtx.beginPath() sourceCtx.moveTo((x1 - active.x) * S.imgW / active.w, (y1 - active.y) * S.imgW / active.w) sourceCtx.lineTo((x2 - active.x) * S.imgW / active.w, (y2 - active.y) * S.imgW / active.w) sourceCtx.stroke() sourceCtx.restore() } S.pickerComposite = null renderObjects() } /** 开始一笔 */ /** 若绘制层已被变换(移动/缩放/旋转),先把结果固化并重置变换参数,保证继续绘制的坐标正确 */ function bakeDrawableLayer(layer) { if (!layer || !isDrawableLayer(layer) || !layer._srcBox) return layer._srcBox = null layer.sourceCanvas = null layer.rotation = 0 layer.x = 0 layer.y = 0 layer.w = S.imgW layer.h = S.imgH layer._bounds = undefined } export function beginStroke() { bakeDrawableLayer(getActiveLayer()) S.strokeCanvas.width = S.imgW S.strokeCanvas.height = S.imgH S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH) // 橡皮擦直接修改活跃图层,不显示独立轨迹层。 S.strokeCanvas.style.display = S.tool === 'eraser' ? 'none' : 'block' S.strokeCanvas.style.opacity = S.brushOpacity } /** 结束一笔:按透明度一次性合成进活跃图层(画笔=正常合成,橡皮=destination-out) */ export function endStroke() { for (const l of S.layers) l._bounds = undefined const ctx = getActiveCtx() if (!ctx) return ctx.save() if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule) if (S.tool === 'eraser') { ctx.globalCompositeOperation = 'destination-out' } ctx.globalAlpha = S.brushOpacity ctx.drawImage(S.strokeCanvas, 0, 0) ctx.restore() S.strokeCanvas.style.display = 'none' const active = getActiveLayer() if (active && active.id === 'draw' && active.sourceCanvas && active.w > 0 && active.h > 0) { const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true }) sourceCtx.save() sourceCtx.globalCompositeOperation = S.tool === 'eraser' ? 'destination-out' : 'source-over' sourceCtx.globalAlpha = S.brushOpacity sourceCtx.translate(-active.x * S.imgW / active.w, -active.y * S.imgH / active.h) sourceCtx.scale(S.imgW / active.w, S.imgH / active.h) sourceCtx.drawImage(S.strokeCanvas, 0, 0) sourceCtx.restore() } S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH) S.pickerComposite = null } /** 圆角半径:夹在短边一半以内,避免圆角把矩形吃掉变胶囊/消失 */ function roundedRadius(s, w, h) { const r = Number(s && s.radius) || 0 if (r <= 0) return 0 return Math.min(r, Math.min(w, h) / 2) } /** 圆角矩形路径:不用 ctx.roundRect(老浏览器没有),手写 arcs,行为可控 */ function roundRectPath(ctx, x, y, w, h, r) { const rr = Math.min(r, Math.min(w, h) / 2) ctx.moveTo(x + rr, y) ctx.arcTo(x + w, y, x + w, y + h, rr) ctx.arcTo(x + w, y + h, x, y + h, rr) ctx.arcTo(x, y + h, x, y, rr) ctx.arcTo(x, y, x + w, y, rr) ctx.closePath() } /** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */ /** 形状描边色:每个形状自己存 color(v1.10 起选项栏可单独调) */ export function strokeOf(s) { return (s && s.color) || S.color } /** 形状填充色:自己设过 fillColor 就用它,否则跟随描边色(同色实心是默认手感) */ export function fillOf(s) { return (s && s.fillColor) || strokeOf(s) } export function drawShape(ctx, s) { ctx.save() ctx.globalAlpha = s.opacity != null ? s.opacity : 1 const rot = s.rotation || 0 if (rot) { const b = shapeBounds(s) 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.strokeStyle = strokeOf(s) ctx.lineWidth = s.lw ctx.lineCap = 'round' ctx.lineJoin = 'round' // v1.17:无描边(strokeOn === false)。老对象没有这个字段,一律当有描边。 // 注意不能靠 lineWidth = 0 实现:canvas 会忽略 0 从而保持上一次的值。 const strokeOn = s.strokeOn !== false if (s.type === 'pen') { const pts = Array.isArray(s.pts) ? s.pts : [] if (pts.length > 1) { ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y) for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y) if (s.closed) ctx.closePath() if (s.closed && s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() } if (strokeOn) ctx.stroke() } } else if (s.type === 'rect') { const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1) const radius = roundedRadius(s, rw, rh) if (radius > 0) { ctx.beginPath() roundRectPath(ctx, rx, ry, rw, rh, radius) if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() } if (strokeOn) ctx.stroke() } else { if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fillRect(rx, ry, rw, rh) } if (strokeOn) ctx.strokeRect(rx, ry, rw, rh) } } else if (s.type === 'circle') { const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2) const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1) ctx.beginPath() ctx.ellipse(rx + rw / 2, ry + rh / 2, Math.max(1, rw / 2), Math.max(1, rh / 2), 0, 0, Math.PI * 2) if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() } if (strokeOn) ctx.stroke() } else if (strokeOn) { // 箭头:没有可填内部,去掉描边等于不画(UI 也不提供这个入口) ctx.fillStyle = strokeOf(s) ctx.beginPath() ctx.moveTo(s.x1, s.y1) ctx.lineTo(s.x2, s.y2) ctx.stroke() const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1) const headLen = Math.max(12, s.lw * 4) ctx.beginPath() ctx.moveTo(s.x2, s.y2) ctx.lineTo(s.x2 - headLen * Math.cos(angle - Math.PI / 6), s.y2 - headLen * Math.sin(angle - Math.PI / 6)) ctx.moveTo(s.x2, s.y2) ctx.lineTo(s.x2 - headLen * Math.cos(angle + Math.PI / 6), s.y2 - headLen * Math.sin(angle + Math.PI / 6)) ctx.stroke() } ctx.restore() } /** 当前工具笔刷半径(图片像素) */ function getToolBrushRadius() { return Math.max(1, S.brushSize) / 2 } /** 图片像素 → 屏幕像素 的换算系数 */ function screenScale() { const rect = S.canvasStack.getBoundingClientRect() return rect.width ? rect.width / S.imgW : S.zoom } /** 清笔刷环专用层(不碰裁剪框 / 选中框 / 蚂蚁线) */ export function clearToolRing() { 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) } /** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */ export function drawToolRing(pos) { clearToolRing() const ctx = S.cursorCtx || S.overlayCtx const r = getToolBrushRadius() const k = 1 / screenScale() const rMin = 2 * k const rr = Math.max(r, rMin) ctx.save() ctx.lineWidth = k ctx.strokeStyle = 'rgba(0,0,0,0.8)' ctx.beginPath() ctx.arc(pos.x, pos.y, rr, 0, Math.PI * 2) ctx.stroke() ctx.strokeStyle = 'rgba(255,255,255,0.9)' ctx.lineWidth = k ctx.beginPath() ctx.arc(pos.x, pos.y, Math.max(rr - k, 0), 0, Math.PI * 2) ctx.stroke() ctx.restore() } // ============ 合成画布(吸管取样 / 导出 / 裁剪共用) ============ /** 合成所有可见图层到一个临时 canvas */ export function getCompositeCanvas() { const c = document.createElement('canvas') c.width = S.imgW c.height = S.imgH const cx = c.getContext('2d', { willReadFrequently: true }) // 与 DOM 叠放 / 图层面板 / 命中测试共用同一份 z 序(唯一真源) cx.globalAlpha = 1 for (const u of layerUnits()) { if (u.obj.visible === false) continue const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas if (!el) continue // 位图的 opacity 由 CSS 显示、这里乘 alpha;矢量对象的不透明度已经画进像素 cx.globalAlpha = u.kind === 'bitmap' ? (u.obj.opacity == null ? 1 : u.obj.opacity) : 1 cx.drawImage(el, 0, 0) } cx.globalAlpha = 1 return c } /** 吸管取样用的合成画布缓存 */ function getPickerComposite() { if (!S.pickerComposite) { S.pickerComposite = getCompositeCanvas().getContext('2d', { willReadFrequently: true }) } return S.pickerComposite } /** 取画布坐标处的合成像素颜色 */ export function sampleColor(pos) { const x = clamp(Math.floor(pos.x), 0, Math.max(0, S.imgW - 1)) const y = clamp(Math.floor(pos.y), 0, Math.max(0, S.imgH - 1)) try { const d = getPickerComposite().getImageData(x, y, 1, 1).data return { r: d[0], g: d[1], b: d[2], a: d[3] } } catch (e) { return null } } /** 吸管悬停预览浮窗 */ export function showPickerTip(e, s) { const tip = runtime.el.querySelector('.iwb-editor-picker-tip') if (!tip) return const chip = tip.querySelector('.iwb-editor-picker-chip') const hex = tip.querySelector('.iwb-editor-picker-hex') if (s && s.a > 0) { const h = rgbToHex(s.r, s.g, s.b) chip.style.background = h chip.style.border = '1px solid rgba(255,255,255,0.3)' hex.textContent = h } else { chip.style.background = 'transparent' chip.style.border = '1px dashed rgba(255,255,255,0.4)' hex.textContent = '透明' } tip.style.display = 'flex' tip.style.left = (e.clientX + 16) + 'px' tip.style.top = (e.clientY + 16) + 'px' } export function hidePickerTip() { const tip = runtime.el.querySelector('.iwb-editor-picker-tip') if (tip) tip.style.display = 'none' } /** 取色完成:切回吸管激活前的工具 */ export function exitPicker() { // 按住 Alt 的临时吸管:取色后不退出(PS 手感:Alt 按住期间可连续吸色), // 由 keyup / 窗口失焦时的 endAltPicker() 统一收尾回到原工具 if (S.altPicker) { S.pickerComposite = null hidePickerTip() return } S.tool = (S.prevTool && S.prevTool !== 'picker') ? S.prevTool : 'brush' S.prevTool = null // 回到的若不是选择/形状类工具,选中态按 setTool 同一套规则清掉,避免画布残留选中框 const back = S.tool // 与 setTool 同一套规则(v1.3):只有选择工具保留选中态 if (back !== 'select') { S.selectedLayerId = null S.selectedTextId = null S.selectedShapeId = null } S.pickerComposite = null hidePickerTip() updateToolUI() updateBrushParamUI() if (S.tool === 'crop') { showCropBar() updateCropInfo() } else { cancelCrop() hideCropBar() } // 回到上一个工具后选项栏由 updateToolUI() → renderOptionBar() 按新工具重建 renderObjects() } /** * PS 手感:画笔 / 橡皮下按住 Alt 临时变成吸管,松开 Alt 回到原工具。 * 只在这两个绘制工具下生效;正在描笔时(isDrawing)不打断。 * 取色后不退出吸管(见 exitPicker 的 altPicker 分支),可以按住 Alt 连续吸色。 */ export function beginAltPicker() { if (S.altPicker) return if (S.tool !== 'brush' && S.tool !== 'eraser') return if (S.isDrawing) return S.altPicker = true setTool('picker') // setTool 会把原工具存进 prevTool,松开 Alt 时用它还原 } /** 松开 Alt / 窗口失焦:结束临时吸管并回到原工具 */ export function endAltPicker() { if (!S.altPicker) return S.altPicker = false exitPicker() } /** 统一颜色应用:设置当前色 + 同步选中文字/形状颜色。 * opts.skipHistory:连续取色(拖 SV/色相条)时由调用方在拖动开始时已拍过快照, * 这里不再逐步 saveSnapshot —— 否则拖一下就是几百张全画质 ImageData。 */ export function applyColorChange(color, opts) { const skipHistory = !!(opts && opts.skipHistory) S.color = color // 只有「确认型」改色才进最近使用:拖 SV 时 skipHistory=true 每帧都调, // 全记进去会把最近色刷成一串相邻色,毫无用处。 if (!skipHistory) rememberColor(color) updateColorUI() const t = getSelectedText() if (t && !t.locked && t.color !== S.color) { if (!skipHistory) saveSnapshot() t.color = S.color renderObjects() } const sh = getSelectedShape() if (sh && !sh.locked && S.tool !== 'text' && (sh.color !== S.color || sh.strokeOn === false)) { // v1.17:给「无描边」的形状选颜色 = 想再看见描边,顺手打开。 // 与改色共用同一张快照,撤销一步就能回到「无描边 + 旧色」。 const revive = sh.strokeOn === false if (!skipHistory) saveSnapshot() sh.color = S.color if (revive) { sh.strokeOn = true; S.shapeStrokeOn = true } renderObjects() } } /** 切换工具(工具栏按钮、快捷键、调色板吸色共用)。保留同类形状选中以便继续编辑。 */ export function setTool(tool) { if (S.placingImage) cancelImagePlacement() commitTextInput() // 用户主动切到别的工具 = 放弃「按住 Alt 临时吸管」,否则松 Alt 会把工具抢回去 if (tool !== 'picker') S.altPicker = false // 钢笔节点编辑与文字编辑都只属于 V(v1.5):切到任何创建类工具都退出编辑态, // 否则从 V 带着 penEditId 切到 P 会出现「钢笔下能拖节点但点不动」的半状态。 if (tool !== 'select') { S.penEditId = null; S.penDragPt = -1; S.penDragPending = null } if (tool === 'picker' && S.tool !== 'picker') S.prevTool = S.tool if (tool !== 'pen') S.penPath = null // 选区与裁剪互斥:进裁剪必须清掉选区;离开选区工具要丢弃未完成的拉框/套索 if (tool === 'crop') { S.selection = null; S.marquee = null; S.lassoPts = null } if (tool !== 'marquee' && tool !== 'lasso') { if (S.marquee || S.lassoPts) { S.isDrawing = false; S.interaction = 'idle' } S.marquee = null S.lassoPts = null } S.tool = tool // 吸管是临时取色工具:必须保留选中态,否则「选中形状 → 按 I 取色」时选中被清掉, // applyColorChange 找不到对象,颜色只写进画笔色、形状不变(用户反馈 2026-11-04) // 选中态只属于「选择(V)」与临时吸管(v1.3,用户裁定 2026-11-05): // 矩形/圆形/箭头/钢笔/文字都只负责新建,切过去就清掉选中 —— // 否则矢量工具下点到已有图形会被当成拖动它,没法在它上面继续画。 const keepSel = tool === 'select' || tool === 'picker' if (!keepSel) { S.selectedLayerId = null S.selectedTextId = null S.selectedShapeId = null } S.bitmapDrag = null S.textDrag = null S.shapeDrag = null S.pickerComposite = null S.lastClick = null // 切工具即断掉双击序列,避免拿上一个工具的最后一次点击配对 hidePickerTip() updateToolUI() updateBrushParamUI() if (tool === 'crop') { showCropBar() updateCropInfo() } else { cancelCrop() hideCropBar() } renderObjects() renderLayerPanel() // 让蚂蚁线/浮动条按新的工具与选区状态同步(由 index.js 注入) if (S.renderAll) S.renderAll() }