上一次提交停在 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=
2122 lines
91 KiB
JavaScript
2122 lines
91 KiB
JavaScript
/* events.js - 事件绑定与 UI 更新
|
||
* 节:鼠标事件、缩放、UI 更新、事件绑定。
|
||
* bindEvents 绑定工具栏/面板,bindCanvasEvents 绑定画布;
|
||
* 所有交互最终改写 state.js 的 S,再由 updateAllUI 刷新界面。
|
||
*/
|
||
|
||
'use strict'
|
||
|
||
import { S, ZOOM_STEP, runtime } from './state.js'
|
||
import { ROT_CURSOR, clamp, getPos, isOverRotationHandle, setView, setZoomActual, setZoomFit, zoomStep } from './viewport.js'
|
||
import { addBitmapLayer, addBlankLayer, applyBitmapDrag, beginBitmapDrag, clearSelection, deleteLayer, ensureWritableLayer, getActiveCtx, getActiveLayer, hitBitmapHandle, mergeLayers, mergeVisibleLayers, removeVecCanvas, renderLayerPanel } from './layers.js'
|
||
import { applyColorChange, beginAltPicker, beginStroke, clearToolRing, drawToolRing, endAltPicker, endStroke, eraseSegment, exitPicker, hidePickerTip, sampleColor, setTool, showPickerTip, strokeSegment } from './tools.js'
|
||
import { beginMarquee, updateMarquee, endMarquee, beginLasso, updateLasso, endLasso, clearMarquee, syncAnts, renderSelection } from './selection.js'
|
||
import { runCommand, toast } from './commands.js'
|
||
import { showSelectionContext, hideSelectionContext } from './floating.js'
|
||
import { applyConstraintDrag, cancelCrop, clearOverlay, confirmCrop, drawCropPreview, hideCropBar, hitCropHandle, insideRect, resizeCropRect, setConstraint, showCropBar, updateCropInfo } from './crop.js'
|
||
import { applyShapeHandle, beginPenEdit, beginShapeHandleDrag, beginTextRotate, beginTextScaleDrag, commitTextInput, deleteSelectedShape, deleteSelectedText, exitPenEdit, getPenEditingShape, getSelectedShape, getSelectedText, hideTextInput, hitAnyObject, hitPenEdgeInsert, hitPenPoint, hitShapeHandle, hitShapeLayer, hitTextHandle, hitTextLayer, hitTopmost, moveLayer, renderObjects, selectNeighborLayer, selectUnit, shapeBounds, showTextInput } from './objects.js'
|
||
import { cancelImagePlacement, confirmImagePlacement, drawPlacementPreview, hitPlacementHandle, insidePlacementRect, resizePlacement } from './placement.js'
|
||
import { close, exportResult } from './index.js'
|
||
import { loadImage } from './dom.js'
|
||
import { pushHistory, redo, resetDraw, restoreOriginal, restoreAll, saveSnapshot, snapshotState, undo } from './history.js'
|
||
import { applyQuickEffect } from './effects.js'
|
||
import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||
|
||
|
||
// ============ 鼠标事件 ============
|
||
/**
|
||
* 防坑注释(两件事,别踩):
|
||
* 1) 三张分发表(MOUSE_DOWN / DRAW_MOVE / DRAW_UP)引用的都是文件后置的 function 声明,
|
||
* 靠函数声明提升生效;若改成 const 箭头函数,表初始化时会抛 TDZ ReferenceError
|
||
* —— 要改必须先把处理器定义挪到表之前。
|
||
* 2) 守卫不对称(原实现如此,勿顺手"统一"):onMouseMove 的放置拖拽要求
|
||
* placingImage && placingHandle && placingStart,而 onMouseUp 只要求 placingImage && placingHandle;
|
||
* 平移同理(move 要求 panStart,up 只要求 panning)。
|
||
*/
|
||
/** 工具按下分发表:公共前置逻辑(放置/平移/按钮/钢笔编辑)走完后按 S.tool 派发到对应处理器 */
|
||
const MOUSE_DOWN_HANDLERS = {
|
||
select: onSelectMouseDown,
|
||
crop: onCropMouseDown,
|
||
text: onTextMouseDown,
|
||
picker: onPickerMouseDown,
|
||
brush: onBrushMouseDown,
|
||
eraser: onEraserMouseDown,
|
||
pen: onPenMouseDown,
|
||
rect: onShapeMouseDown,
|
||
arrow: onShapeMouseDown,
|
||
circle: onShapeMouseDown
|
||
}
|
||
|
||
function onMouseDown(e) {
|
||
// 图片放置模式优先处理
|
||
if (S.placingImage) { onPlacementMouseDown(e); return }
|
||
|
||
if (S.spaceDown || S.tool === 'hand' || e.button === 1) { onPanMouseDown(e); return }
|
||
if (e.button !== 0) return
|
||
e.preventDefault()
|
||
|
||
const pos = getPos(e)
|
||
S.startX = pos.x
|
||
S.startY = pos.y
|
||
hideSelectionContext()
|
||
// 点画布视为离开图层面板:退出「合并多选」,免得下次 Ctrl+E 合到看不见的旧集合上
|
||
if (S.layerMulti.length) { S.layerMulti.length = 0; renderLayerPanel() }
|
||
|
||
// 选区工具:拉框 / 套索期间独占交互,不与选择/绘制/裁剪分支纠缠
|
||
if (S.tool === 'marquee') { beginMarquee(pos); return }
|
||
if (S.tool === 'lasso') { beginLasso(pos); return }
|
||
|
||
// 双击:V 下进对象编辑(钢笔节点 / 文字内容),P 下结束当前路径。
|
||
// 自己判而不听 dblclick 事件 —— 画布上选中态重绘会让浏览器换掉命中元素,
|
||
// 实测 dblclick 根本不派发(无头环境 100% 复现),而 mousedown 一定有。
|
||
const dbl = isDoubleClick(pos)
|
||
if (S.tool === 'select') {
|
||
if (dbl && onCanvasDoubleClick(e, pos)) return
|
||
// 钢笔节点编辑优先(只属于 V,v1.5):点节点/点边直接接管;点空白退出编辑后继续走下方工具逻辑
|
||
const penShape = getPenEditingShape()
|
||
if (penShape && onPenEditMouseDown(e, pos, penShape)) return
|
||
}
|
||
if (S.tool === 'pen' && dbl) { commitPenPath(); return }
|
||
|
||
const handler = Object.prototype.hasOwnProperty.call(MOUSE_DOWN_HANDLERS, S.tool) ? MOUSE_DOWN_HANDLERS[S.tool] : null
|
||
if (handler) handler(pos, e)
|
||
}
|
||
|
||
/**
|
||
* 自算双击:同一位置 380ms 内两次 mousedown。
|
||
* 命中一次后清空记录,三连击不会重复触发。
|
||
*/
|
||
const DBL_INTERVAL = 380
|
||
function isDoubleClick(pos) {
|
||
const now = (typeof performance !== 'undefined' && performance.now) ? performance.now() : Date.now()
|
||
const last = S.lastClick
|
||
const hit = !!last && (now - last.t) < DBL_INTERVAL &&
|
||
Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / S.zoom, 6)
|
||
S.lastClick = hit ? null : { t: now, x: pos.x, y: pos.y }
|
||
return hit
|
||
}
|
||
|
||
/**
|
||
* 双击语义(只属于 V,v1.5 用户裁定):
|
||
* 编辑中的钢笔删节点 > 未编辑的钢笔进节点编辑 > 文字进内容编辑。
|
||
* 返回 true 表示已接管,不再走单击逻辑。
|
||
*/
|
||
function onCanvasDoubleClick(e, pos) {
|
||
const penShape = getPenEditingShape()
|
||
if (penShape) {
|
||
const pi = hitPenPoint(pos, penShape, Math.max(14 / S.zoom, 8))
|
||
if (pi < 0) return false
|
||
e.preventDefault()
|
||
saveSnapshot()
|
||
const pts = penShape.pts
|
||
const minPts = penShape.closed ? 3 : 2
|
||
if (pts.length <= minPts) {
|
||
removeVecCanvas(penShape)
|
||
S.shapeLayers = S.shapeLayers.filter(x => x.id !== penShape.id)
|
||
S.penEditId = null
|
||
S.selectedShapeId = null
|
||
} else {
|
||
pts.splice(pi, 1)
|
||
if (penShape.closed && pts.length < 3) penShape.closed = false
|
||
}
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
return true
|
||
}
|
||
const hitPen = hitShapeLayer(pos, true)
|
||
if (hitPen && hitPen.type === 'pen') {
|
||
e.preventDefault()
|
||
beginPenEdit(hitPen)
|
||
return true
|
||
}
|
||
const hitText = hitTextLayer(pos)
|
||
if (hitText) {
|
||
e.preventDefault()
|
||
selectUnit('text', hitText.id)
|
||
if (hitText.locked) return true
|
||
renderObjects()
|
||
showTextInput(hitText.x, hitText.y, hitText)
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
/** 图片放置模式的按下:命中手柄/图内开始拖拽,点外部确认放置 */
|
||
function onPlacementMouseDown(e) {
|
||
e.preventDefault()
|
||
const pos = getPos(e)
|
||
const handle = hitPlacementHandle(pos)
|
||
if (handle) {
|
||
S.placingHandle = handle
|
||
S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h, rotation: S.placingImage.rotation || 0 }
|
||
S.drawCanvasCursor(CROP_CURSORS[handle] || 'move')
|
||
return
|
||
}
|
||
if (insidePlacementRect(pos)) {
|
||
S.placingHandle = 'move'
|
||
S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, rotation: S.placingImage.rotation || 0 }
|
||
S.drawCanvasCursor('move')
|
||
return
|
||
}
|
||
// 点击外部 = 确认放置
|
||
confirmImagePlacement()
|
||
}
|
||
|
||
/** 空格/抓手工具/中键:提交文字输入并开始平移画布 */
|
||
function onPanMouseDown(e) {
|
||
e.preventDefault()
|
||
commitTextInput()
|
||
S.panning = true
|
||
S.panStart = { x: e.clientX, y: e.clientY, vx: S.viewX || 0, vy: S.viewY || 0 }
|
||
updateCursor()
|
||
}
|
||
|
||
/** 钢笔节点编辑中的按下:点节点拖动/点边插点返回 true(已接管);点空白退出编辑返回 false 继续走工具逻辑 */
|
||
function onPenEditMouseDown(e, pos, penShape) {
|
||
const pi = hitPenPoint(pos, penShape, Math.max(16 / S.zoom, 9))
|
||
if (pi >= 0) {
|
||
S.penDragPt = pi
|
||
S.penDragBase = JSON.parse(JSON.stringify(penShape.pts))
|
||
S.penDragPending = snapshotState()
|
||
return true
|
||
}
|
||
const ei = hitPenEdgeInsert(pos, penShape)
|
||
if (ei >= 0) {
|
||
saveSnapshot()
|
||
penShape.pts.splice(ei + 1, 0, { x: pos.x, y: pos.y })
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
return true
|
||
}
|
||
// 点击空白:退出编辑(继续走工具原有新建/选择逻辑)
|
||
S.penEditId = null
|
||
S.penDragPt = -1
|
||
S.penDragPending = null
|
||
renderObjects()
|
||
return false
|
||
}
|
||
|
||
/** 选择工具的按下:手柄 > 统一 z 序命中最上层 > 清空选择。
|
||
* 旧实现「先 hitAnyObject(只看矢量) 再 hitBitmapLayer(只看位图)」两段各自排序,
|
||
* 从不比较位图与矢量的 z ⇒ 截图下面有图形时永远选不中截图,排序按钮也跟着作用错对象。 */
|
||
function onSelectMouseDown(pos) {
|
||
if (commitTextInput()) return
|
||
const bitmapHandle = hitBitmapHandle(pos)
|
||
if (bitmapHandle) { beginBitmapDrag(bitmapHandle, pos); return }
|
||
const th = hitTextHandle(pos)
|
||
if (th) { if (th === 'rotate') beginTextRotate(pos); else beginTextScaleDrag(th, pos); return }
|
||
const shH = hitShapeHandle(pos)
|
||
if (shH) { beginShapeHandleDrag(shH, pos); return }
|
||
const hit = hitTopmost(pos)
|
||
if (!hit) {
|
||
selectUnit(null, null)
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
selectUnit(hit.kind, hit.obj.id)
|
||
if (hit.obj.locked) { renderObjects(); renderLayerPanel(); return }
|
||
if (hit.kind === 'bitmap') {
|
||
S.activeLayerId = hit.obj.id
|
||
beginBitmapDrag(null, pos)
|
||
} else if (hit.kind === 'text') {
|
||
S.textDrag = { mode: 'move', start: pos, layer: { x: hit.obj.x, y: hit.obj.y }, pending: snapshotState() }
|
||
} else {
|
||
S.shapeDrag = { mode: 'move', start: pos, shape: { ...hit.obj }, pending: snapshotState() }
|
||
}
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
|
||
/** 裁剪工具的按下:已有选区则拖手柄/整框移动,否则开始拉新选框 */
|
||
function onCropMouseDown(pos) {
|
||
if (S.cropRect) {
|
||
const handle = hitCropHandle(pos)
|
||
if (handle) { S.cropHandle = handle; S.isDrawing = true; return }
|
||
if (insideRect(pos, S.cropRect)) {
|
||
S.cropMoving = true
|
||
S.moveStart = { x: pos.x, y: pos.y, rect: { ...S.cropRect } }
|
||
S.isDrawing = true
|
||
}
|
||
return
|
||
}
|
||
S.isDrawing = true
|
||
}
|
||
|
||
/** 文字工具的按下:只负责「在点击处新建文字」。
|
||
* v1.3(用户裁定 2026-11-05):与矢量工具同一套规则 —— 点已有文字不再选中/移动它,
|
||
* 否则想在文字上叠一段新文字时会被当成拖旧文字。选中/移动/缩放交给 V;
|
||
* 改内容 = V 下双击(T 下双击沿用旧行为,仍可直接改)。 */
|
||
function onTextMouseDown(pos) {
|
||
if (commitTextInput()) return
|
||
if (S.selectedTextId) { S.selectedTextId = null; renderObjects(); renderLayerPanel() }
|
||
showTextInput(pos.x, pos.y)
|
||
}
|
||
|
||
/** 吸管工具的按下:取样并应用颜色后退出吸管模式 */
|
||
function onPickerMouseDown(pos) {
|
||
const s = sampleColor(pos)
|
||
if (s && s.a > 0) {
|
||
applyColorChange(rgbToHex(s.r, s.g, s.b))
|
||
}
|
||
exitPicker()
|
||
return
|
||
}
|
||
|
||
/** 画笔工具的按下:无可写图层则自动落「标注」层(用户裁定:默认不预建画笔层),
|
||
* 否则存快照并落下第一点。注意 ensureWritableLayer 必须在 saveSnapshot 之前,
|
||
* 让首笔 Ctrl+Z 连自动建的层一起撤掉。
|
||
* 选中态同步:面板高亮(selectedLayerId)必须跟随真正的绘制目标(activeLayerId),
|
||
* 否则会出现「面板没选中这层却能画上去」的逻辑矛盾(用户反馈 2026-11-04)。 */
|
||
function onBrushMouseDown(pos) {
|
||
const layer = ensureWritableLayer()
|
||
if (!layer) return
|
||
S.selectedLayerId = layer.id
|
||
S.isDrawing = true
|
||
saveSnapshot()
|
||
beginStroke()
|
||
strokeSegment(pos.x, pos.y, pos.x, pos.y)
|
||
}
|
||
|
||
/** 橡皮工具的按下:与画笔同构但**不自动建层**(减内容语义,没有可擦的内容就不该凭空建层),
|
||
* 同样把面板高亮同步到真正的擦除目标。
|
||
* 兜底:默认的「原图」层是锁定态,此时退到最上层可写的标注层 ——
|
||
* 否则用户刚打开图就用橡皮,会表现为「橡皮完全没反应」(2026-11-04 反馈)。 */
|
||
function onEraserMouseDown(pos) {
|
||
let layer = getActiveLayer()
|
||
if (!layer || layer.locked) layer = topWritableLayer()
|
||
if (!layer) { toast('没有可擦的图层:先用画笔标注,或在图层面板新建一层', 'info'); return }
|
||
S.activeLayerId = layer.id
|
||
S.selectedLayerId = layer.id
|
||
S.isDrawing = true
|
||
saveSnapshot()
|
||
beginStroke()
|
||
eraseSegment(pos.x, pos.y, pos.x, pos.y)
|
||
}
|
||
|
||
/** 最上层可写(未锁定/可见)的标注图层;没有返回 null */
|
||
function topWritableLayer() {
|
||
let hit = null
|
||
for (const l of S.layers) {
|
||
if (l.locked || l.visible === false) continue
|
||
if (!hit || (l.z || 0) >= (hit.z || 0)) hit = l
|
||
}
|
||
return hit
|
||
}
|
||
|
||
/** 钢笔工具的按下:回到起点则闭合路径,否则追加一个路径点 */
|
||
function onPenMouseDown(pos) {
|
||
if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false }
|
||
const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) }
|
||
const first = S.penPath.pts[0]
|
||
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)) {
|
||
S.penPath.closed = true
|
||
S.penPath.nearStart = true
|
||
S.penPath.preview = null
|
||
commitPenPath()
|
||
} else {
|
||
S.penPath.pts.push(point)
|
||
renderObjects({ id: 'pen-preview', type: 'pen', pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: false, opacity: 1, visible: true })
|
||
}
|
||
return
|
||
}
|
||
|
||
/** 矩形/圆形/箭头的按下:只负责「起笔新建」。
|
||
* v1.3(用户裁定 2026-11-05):矢量工具不再具备选择功能 —— 以前这里先试手柄、
|
||
* 再命中同类型形状并拖动它,于是在已有矩形上面按下会被当成拖旧矩形,
|
||
* 根本没法在它上面继续画。选中/移动/改尺寸统一交给 V(选择工具)。 */
|
||
function onShapeMouseDown(pos) {
|
||
if (S.selectedShapeId) { S.selectedShapeId = null; renderObjects(); renderLayerPanel() }
|
||
S.isDrawing = true
|
||
}
|
||
|
||
/** 绘制中移动分发表:公共前置(放置/平移/各拖拽态/isDrawing)走完后按 S.tool 派发到对应处理器 */
|
||
// 同 MOUSE_DOWN_HANDLERS:依赖 function 声明提升,勿改成 const 箭头函数
|
||
const DRAW_MOVE_HANDLERS = {
|
||
brush: onBrushDrawMove,
|
||
eraser: onEraserDrawMove,
|
||
pen: onPenDrawMove,
|
||
rect: onShapeDrawMove,
|
||
arrow: onShapeDrawMove,
|
||
circle: onShapeDrawMove,
|
||
crop: onCropDrawMove
|
||
}
|
||
|
||
function onMouseMove(e) {
|
||
// 图片放置拖拽
|
||
if (S.placingImage && S.placingHandle && S.placingStart) {
|
||
onPlacementDragMove(e); return
|
||
}
|
||
// 图片放置 hover 光标
|
||
if (S.placingImage) {
|
||
onPlacementHoverMove(e); return
|
||
}
|
||
|
||
if (S.panning && S.panStart) {
|
||
onPanMouseMove(e); return
|
||
}
|
||
const pos0 = getPos(e)
|
||
if (S.marquee) { updateMarquee(pos0); return }
|
||
if (S.lassoPts) { updateLasso(pos0); return }
|
||
if (S.bitmapDrag) {
|
||
onBitmapDragMouseMove(pos0); return
|
||
}
|
||
if (S.textDrag) {
|
||
onTextDragMouseMove(pos0); return
|
||
}
|
||
if (S.penDragPt >= 0) {
|
||
onPenEditDragMove(pos0); return
|
||
}
|
||
if (S.shapeDrag) {
|
||
onShapeDragMouseMove(pos0); return
|
||
}
|
||
if (!S.isDrawing) return
|
||
const pos = pos0
|
||
|
||
const handler = Object.prototype.hasOwnProperty.call(DRAW_MOVE_HANDLERS, S.tool) ? DRAW_MOVE_HANDLERS[S.tool] : null
|
||
if (handler) handler(pos)
|
||
}
|
||
|
||
/** 图片放置拖拽:按手柄/整体拖拽调整放置框并刷新预览 */
|
||
function onPlacementDragMove(e) {
|
||
const pos = getPos(e)
|
||
resizePlacement(pos)
|
||
drawPlacementPreview()
|
||
return
|
||
}
|
||
|
||
/** 图片放置 hover:按命中手柄/区域切换画布光标 */
|
||
function onPlacementHoverMove(e) {
|
||
const pos = getPos(e)
|
||
const h = hitPlacementHandle(pos)
|
||
if (h) S.drawCanvasCursor(h === 'rotate' ? ROT_CURSOR : (CROP_CURSORS[h] || 'move'))
|
||
else S.drawCanvasCursor(insidePlacementRect(pos) ? 'move' : 'default')
|
||
return
|
||
}
|
||
|
||
/** 平移:按鼠标位移更新画布视口 */
|
||
function onPanMouseMove(e) {
|
||
setView(S.panStart.vx + (e.clientX - S.panStart.x),
|
||
S.panStart.vy + (e.clientY - S.panStart.y))
|
||
return
|
||
}
|
||
|
||
/** 位图层拖拽:应用位移/缩放并重绘对象层 */
|
||
function onBitmapDragMouseMove(pos0) {
|
||
applyBitmapDrag(pos0)
|
||
renderObjects()
|
||
return
|
||
}
|
||
|
||
/** 文字拖拽:按模式移动/旋转/缩放选中文字后重绘 */
|
||
function onTextDragMouseMove(pos0) {
|
||
const t = getSelectedText()
|
||
if (t) {
|
||
if (S.textDrag.mode === 'move') {
|
||
const dx = pos0.x - S.textDrag.start.x
|
||
const dy = pos0.y - S.textDrag.start.y
|
||
t.x = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4))
|
||
t.y = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4))
|
||
} else if (S.textDrag.mode === 'rotate') {
|
||
const st = S.textDrag
|
||
const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx)
|
||
const a0 = Math.atan2(st.startY0 - st.cy, st.startX0 - st.cx)
|
||
let deg = st.rotation
|
||
if (st.startX0 !== undefined) deg = st.rotation + (a1 - a0) * 180 / Math.PI
|
||
if (S._shiftDown) deg = Math.round(deg / 15) * 15
|
||
t.rotation = deg
|
||
} else if (S.textDrag.mode === 'scale') {
|
||
const dx = pos0.x - S.textDrag.anchor.x
|
||
const dy = pos0.y - S.textDrag.anchor.y
|
||
const d = Math.sqrt(dx * dx + dy * dy)
|
||
const f = d / Math.max(S.textDrag.d0, 1)
|
||
t.fontSize = clamp(Math.round(S.textDrag.fontSize * f), 8, 2000)
|
||
}
|
||
renderObjects()
|
||
}
|
||
return
|
||
}
|
||
|
||
/** 钢笔节点拖拽:更新当前顶点坐标并重绘 */
|
||
function onPenEditDragMove(pos0) {
|
||
const penShape = getPenEditingShape()
|
||
if (penShape && penShape.pts[S.penDragPt]) {
|
||
penShape.pts[S.penDragPt].x = clamp(pos0.x, 0, S.imgW)
|
||
penShape.pts[S.penDragPt].y = clamp(pos0.y, 0, S.imgH)
|
||
renderObjects()
|
||
}
|
||
return
|
||
}
|
||
|
||
/** 形状拖拽:整体移动按画布边界夹取,或走手柄变形,再重绘对象层 */
|
||
function onShapeDragMouseMove(pos0) {
|
||
const sh = getSelectedShape()
|
||
if (sh) {
|
||
if (S.shapeDrag.mode === 'move') {
|
||
const dx = pos0.x - S.shapeDrag.start.x
|
||
const dy = pos0.y - S.shapeDrag.start.y
|
||
const b = shapeBounds(S.shapeDrag.shape)
|
||
const cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w)))
|
||
const cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h)))
|
||
if (sh.type === 'pen') {
|
||
sh.pts = (S.shapeDrag.shape.pts || []).map(p => ({ x: p.x + cdx, y: p.y + cdy }))
|
||
} else {
|
||
sh.x1 = S.shapeDrag.shape.x1 + cdx
|
||
sh.y1 = S.shapeDrag.shape.y1 + cdy
|
||
sh.x2 = S.shapeDrag.shape.x2 + cdx
|
||
sh.y2 = S.shapeDrag.shape.y2 + cdy
|
||
}
|
||
} else {
|
||
applyShapeHandle(sh, S.shapeDrag.handle, pos0)
|
||
}
|
||
renderObjects()
|
||
}
|
||
return
|
||
}
|
||
|
||
/** 画笔绘制:延伸笔段、更新起点并刷新笔刷环 */
|
||
function onBrushDrawMove(pos) {
|
||
strokeSegment(S.startX, S.startY, pos.x, pos.y)
|
||
S.startX = pos.x
|
||
S.startY = pos.y
|
||
drawToolRing(pos)
|
||
}
|
||
|
||
/** 橡皮绘制:擦除延伸段、更新起点并刷新笔刷环 */
|
||
function onEraserDrawMove(pos) {
|
||
eraseSegment(S.startX, S.startY, pos.x, pos.y)
|
||
S.startX = pos.x
|
||
S.startY = pos.y
|
||
drawToolRing(pos)
|
||
}
|
||
|
||
/** 钢笔路径预览:更新悬停点与起点闭合提示 */
|
||
function onPenDrawMove(pos) {
|
||
if (S.penPath) { S.penPath.preview = pos; const first = S.penPath.pts[0]
|
||
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / S.zoom, S.shapeLineWidth * 1.5)
|
||
S.penPath.nearStart = !!nearStart
|
||
renderObjects() }
|
||
}
|
||
|
||
/** 矩形/圆/箭头拉框:渲染临时形状预览 */
|
||
function onShapeDrawMove(pos) {
|
||
const temp = {
|
||
id: 'temp',
|
||
type: S.tool,
|
||
x1: S.startX, y1: S.startY,
|
||
x2: pos.x, y2: pos.y,
|
||
color: S.color,
|
||
lw: Math.max(1, S.shapeLineWidth),
|
||
lineWidth: Math.max(1, S.shapeLineWidth),
|
||
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
|
||
opacity: 1,
|
||
visible: true
|
||
}
|
||
renderObjects(temp)
|
||
}
|
||
|
||
/** 裁剪拉框/手柄拖拽/整框移动:刷新选区预览与裁剪信息 */
|
||
function onCropDrawMove(pos) {
|
||
if (S.cropHandle) {
|
||
resizeCropRect(pos)
|
||
drawCropPreview()
|
||
updateCropInfo()
|
||
} else if (S.cropMoving && S.moveStart) {
|
||
const dx = pos.x - S.moveStart.x
|
||
const dy = pos.y - S.moveStart.y
|
||
const r = S.moveStart.rect
|
||
const nx = r.x + dx
|
||
const ny = r.y + dy
|
||
S.cropRect = { x: nx, y: ny, w: r.w, h: r.h }
|
||
drawCropPreview()
|
||
updateCropInfo()
|
||
} else {
|
||
drawCropPreview(S.startX, S.startY, pos.x, pos.y)
|
||
updateCropInfo()
|
||
}
|
||
}
|
||
|
||
/** 绘制结束分发表:isDrawing 收尾与状态复位后按 S.tool 派发到对应收尾处理器 */
|
||
// 同 MOUSE_DOWN_HANDLERS:依赖 function 声明提升,勿改成 const 箭头函数
|
||
const DRAW_UP_HANDLERS = {
|
||
brush: onStrokeDrawUp,
|
||
eraser: onStrokeDrawUp,
|
||
crop: onCropDrawUp,
|
||
rect: onShapeDrawUp,
|
||
arrow: onShapeDrawUp,
|
||
circle: onShapeDrawUp
|
||
}
|
||
|
||
function onMouseUp(e) {
|
||
if (S.marquee) { endMarquee(); return }
|
||
if (S.lassoPts) { endLasso(); return }
|
||
if (S.penDragPt >= 0) {
|
||
onPenEditMouseUp(); return
|
||
}
|
||
// 图片放置拖拽结束
|
||
if (S.placingImage && S.placingHandle) {
|
||
onPlacementMouseUp(); return
|
||
}
|
||
if (S.panning) {
|
||
onPanMouseUp(); return
|
||
}
|
||
if (S.textDrag) {
|
||
onTextDragMouseUp(); return
|
||
}
|
||
if (S.bitmapDrag) {
|
||
onBitmapDragMouseUp(); return
|
||
}
|
||
if (S.shapeDrag) {
|
||
onShapeDragMouseUp(); return
|
||
}
|
||
if (!S.isDrawing) return
|
||
S.isDrawing = false
|
||
const pos = getPos(e)
|
||
|
||
const handler = Object.prototype.hasOwnProperty.call(DRAW_UP_HANDLERS, S.tool) ? DRAW_UP_HANDLERS[S.tool] : null
|
||
if (handler) handler(pos)
|
||
}
|
||
|
||
/** 钢笔节点拖拽收尾:复位拖拽态并按差异入栈历史 */
|
||
function onPenEditMouseUp() {
|
||
const penShape = getPenEditingShape()
|
||
const pending = S.penDragPending
|
||
S.penDragPt = -1
|
||
S.penDragPending = null
|
||
S.penDragBase = null
|
||
if (pending && penShape) {
|
||
const cur = snapshotState({ metaOnly: true })
|
||
if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes)) {
|
||
pushHistory(S.history, pending)
|
||
S.redoStack = []
|
||
}
|
||
}
|
||
return
|
||
}
|
||
|
||
/** 图片放置拖拽结束:清手柄与起点并刷新预览 */
|
||
function onPlacementMouseUp() {
|
||
S.placingHandle = null
|
||
S.placingStart = null
|
||
drawPlacementPreview()
|
||
return
|
||
}
|
||
|
||
/** 平移结束:复位平移态并刷新光标 */
|
||
function onPanMouseUp() {
|
||
S.panning = false
|
||
S.panStart = null
|
||
updateCursor()
|
||
return
|
||
}
|
||
|
||
/** 文字拖拽收尾:按差异入栈历史并刷新图层面板 */
|
||
function onTextDragMouseUp() {
|
||
const pending = S.textDrag.pending
|
||
if (pending) {
|
||
const cur = snapshotState({ metaOnly: true })
|
||
if (JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) {
|
||
pushHistory(S.history, pending)
|
||
S.redoStack = []
|
||
}
|
||
}
|
||
S.textDrag = null
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
|
||
/** 位图层拖拽收尾:按位图差异入栈历史并重绘 */
|
||
function onBitmapDragMouseUp() {
|
||
const pending = S.bitmapDrag.pending
|
||
if (pending) {
|
||
const cur = snapshotState({ metaOnly: true })
|
||
const before = pending.bitmaps.find(b => b.id === S.selectedLayerId)
|
||
const after = cur.bitmaps.find(b => b.id === S.selectedLayerId)
|
||
if (before && after && JSON.stringify([before.x, before.y, before.w, before.h]) !== JSON.stringify([after.x, after.y, after.w, after.h])) {
|
||
pushHistory(S.history, pending)
|
||
S.redoStack = []
|
||
}
|
||
}
|
||
S.bitmapDrag = null
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
|
||
/** 形状拖拽收尾:按差异入栈历史并刷新图层面板 */
|
||
function onShapeDragMouseUp() {
|
||
const pending = S.shapeDrag.pending
|
||
if (pending) {
|
||
const cur = snapshotState({ metaOnly: true })
|
||
if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes) ||
|
||
JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) {
|
||
pushHistory(S.history, pending)
|
||
S.redoStack = []
|
||
}
|
||
}
|
||
S.shapeDrag = null
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
|
||
/** 画笔/橡皮一笔结束:收笔 */
|
||
function onStrokeDrawUp() {
|
||
endStroke()
|
||
return
|
||
}
|
||
|
||
/** 裁剪收尾:手柄/整框拖拽复位,否则按拉框结果确认或清除选区 */
|
||
function onCropDrawUp(pos) {
|
||
if (S.cropHandle) {
|
||
S.cropHandle = null
|
||
drawCropPreview()
|
||
updateCropInfo()
|
||
return
|
||
}
|
||
if (S.cropMoving) {
|
||
S.cropMoving = false
|
||
S.moveStart = null
|
||
drawCropPreview()
|
||
updateCropInfo()
|
||
return
|
||
}
|
||
const r = applyConstraintDrag(S.startX, S.startY, pos.x, pos.y)
|
||
if (r.w > 2 && r.h > 2) {
|
||
S.cropRect = { x: r.x, y: r.y, w: r.w, h: r.h }
|
||
showCropBar()
|
||
drawCropPreview()
|
||
updateCropInfo()
|
||
} else {
|
||
clearOverlay()
|
||
}
|
||
}
|
||
|
||
/** 矩形/圆/箭头拉框结束:尺寸达标则落成新形状,并回到 V 选中它 */
|
||
function onShapeDrawUp(pos) {
|
||
const len = Math.hypot(pos.x - S.startX, pos.y - S.startY)
|
||
const ok = S.tool === 'rect' || S.tool === 'circle'
|
||
? (Math.abs(pos.x - S.startX) > 2 && Math.abs(pos.y - S.startY) > 2)
|
||
: len > 3
|
||
if (ok) {
|
||
saveSnapshot()
|
||
const shape = {
|
||
id: 's' + Date.now() + Math.floor(Math.random() * 1000),
|
||
type: S.tool,
|
||
x1: S.startX, y1: S.startY,
|
||
x2: pos.x, y2: pos.y,
|
||
color: S.color,
|
||
lw: Math.max(1, S.shapeLineWidth),
|
||
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
|
||
opacity: 1,
|
||
visible: true,
|
||
locked: false,
|
||
z: ++S.zCounter
|
||
}
|
||
S.shapeLayers.push(shape)
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
finishCreateTool('shape', shape.id)
|
||
return
|
||
}
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
|
||
/**
|
||
* 创建类工具画完即回 V 并选中新对象(用户 2026-11-05 裁定)。
|
||
* 依据:画完的下一步基本是调位置/颜色/粗细,再手动按一次 V 是多余动作。
|
||
* 顺序必须是「先 setTool('select') 再 selectUnit」—— setTool 里对非选中类工具
|
||
* 会清三个选中 id,反过来选中会被立刻清掉。
|
||
*/
|
||
function finishCreateTool(kind, id) {
|
||
if (['rect', 'circle', 'arrow', 'pen'].indexOf(S.tool) < 0) return
|
||
setTool('select')
|
||
if (!id) return
|
||
selectUnit(kind, id)
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
|
||
// ============ 缩放 ============
|
||
function onWheel(e) {
|
||
if (!S.open) return
|
||
// 底部浮动工具栏在 canvas-wrap 内:在它上面滚轮不该缩放画布(窄窗口时它自己横向滚动)
|
||
if (e.target && e.target.closest && e.target.closest('.iwb-editor-tools')) return
|
||
e.preventDefault()
|
||
const rect = S.canvasWrap.getBoundingClientRect()
|
||
const mx = e.clientX - rect.left
|
||
const my = e.clientY - rect.top
|
||
const factor = e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP
|
||
zoomStep(factor, mx, my)
|
||
}
|
||
|
||
// ============ UI 更新 ============
|
||
export function updateAllUI() {
|
||
updateToolUI()
|
||
updateColorUI()
|
||
updateBrushUI()
|
||
updateBrushParamUI()
|
||
updateFillUI()
|
||
updateLayerUI()
|
||
updateZoomUI()
|
||
hidePickerTip()
|
||
runtime.el.querySelectorAll('.iwb-editor-constraint-btn[data-ratio]').forEach(b => b.classList.remove('active'))
|
||
const freeBtn = runtime.el.querySelector('.iwb-editor-constraint-btn[data-ratio="free"]')
|
||
if (freeBtn) freeBtn.classList.add('active')
|
||
hideCropBar()
|
||
updateCropInfo()
|
||
hideTextInput()
|
||
S.selectedTextId = null
|
||
S.textDrag = null
|
||
S.selectedShapeId = null
|
||
S.shapeDrag = null
|
||
renderLayerPanel()
|
||
}
|
||
|
||
export function updateZoomUI() {
|
||
const val = runtime.el.querySelector('.iwb-editor-zoom-val')
|
||
if (val) val.textContent = Math.round(S.zoom * 100) + '%'
|
||
updateStatusbar()
|
||
}
|
||
|
||
export function updateToolUI() {
|
||
runtime.el.querySelectorAll('.iwb-editor-tool').forEach(btn => {
|
||
btn.classList.toggle('active', btn.dataset.tool === S.tool)
|
||
})
|
||
updateCursor()
|
||
renderOptionBar()
|
||
updateStatusbar()
|
||
}
|
||
|
||
/**
|
||
* 笔刷大小 / 工具变化后立刻按「最后悬停点」重画笔刷环。
|
||
* 不这么做,按 ] / [ 或拖选项栏滑块时只有数值在变,环要等下一次 mousemove 才跟上
|
||
* —— 用户看到的就是「调了大小但光标没变,动一下鼠标才正常」(v1.6 反馈)。
|
||
*/
|
||
export function refreshBrushRing() {
|
||
if (!S.hoverPos) return
|
||
if (S.tool !== 'brush' && S.tool !== 'eraser') return
|
||
if (S.isDrawing) return
|
||
drawToolRing(S.hoverPos)
|
||
}
|
||
|
||
export function updateCursor() {
|
||
if (S.panning) { S.drawCanvasCursor('grabbing'); return }
|
||
if (S.spaceDown) { S.drawCanvasCursor('grab'); return }
|
||
if (S.tool === 'hand') { S.drawCanvasCursor('grab'); return }
|
||
if (S.tool === 'brush' || S.tool === 'eraser') {
|
||
S.drawCanvasCursor('none')
|
||
// 切到画笔/橡皮时鼠标可能已经在画布上停着:直接补画一次环,不用等移动
|
||
refreshBrushRing()
|
||
return
|
||
}
|
||
if (S.tool === 'crop' && S.cropRect) {
|
||
S.drawCanvasCursor('crosshair')
|
||
return
|
||
}
|
||
S.drawCanvasCursor(S.tool === 'text' ? 'text' : (S.tool === 'select' ? 'default' : 'crosshair'))
|
||
}
|
||
|
||
/** 在所有位图图层 canvas 上设置 cursor(因为事件可能落在任意一个上) */
|
||
S.drawCanvasCursor = function(cur) {
|
||
for (const layer of S.layers) {
|
||
layer.canvas.style.cursor = cur
|
||
}
|
||
}
|
||
|
||
export function updateColorUI() {
|
||
let matchPreset = false
|
||
runtime.el.querySelectorAll('.iwb-editor-color[data-color]').forEach(s => {
|
||
const on = (s.dataset.color || '').toLowerCase() === S.color.toLowerCase()
|
||
if (on) matchPreset = true
|
||
s.classList.toggle('active', on)
|
||
})
|
||
const panelHex = runtime.el.querySelector('.iwb-editor-color-hex')
|
||
const hexInput = runtime.el.querySelector('.iwb-editor-color-hex-input')
|
||
if (hexInput && document.activeElement !== hexInput) hexInput.value = S.color.toUpperCase()
|
||
// 工具栏色点:色板收起时它就是唯一的颜色指示,必须始终跟随 S.color
|
||
const colorDot = runtime.el.querySelector('.iwb-editor-color-btn i')
|
||
if (colorDot) colorDot.style.background = S.color
|
||
runtime.el.querySelectorAll('.iwb-editor-color-panel-swatch').forEach(sw => sw.classList.toggle('active', (sw.dataset.panelColor || '').toLowerCase() === S.color.toLowerCase()))
|
||
if (panelHex) panelHex.textContent = S.color.toUpperCase()
|
||
const rgb = hexToRgb(S.color)
|
||
const max = Math.max(rgb.r, rgb.g, rgb.b) / 255, min = Math.min(rgb.r, rgb.g, rgb.b) / 255
|
||
const d = max - min
|
||
let h = 0
|
||
if (d) { if (max === rgb.r / 255) h = 60 * (((rgb.g - rgb.b) / 255 / d) % 6); else if (max === rgb.g / 255) h = 60 * ((rgb.b - rgb.r) / 255 / d + 2); else h = 60 * ((rgb.r - rgb.g) / 255 / d + 4) }
|
||
if (h < 0) h += 360
|
||
const sv = runtime.el.querySelector('.iwb-color-sv'), hue = runtime.el.querySelector('.iwb-color-hue')
|
||
if (sv) sv.style.backgroundColor = `hsl(${h} 100% 50%)`
|
||
if (hue) hue.dataset.hue = h
|
||
const hueMarker = hue && hue.querySelector('span'); if (hueMarker) hueMarker.style.top = (h / 360 * 100) + '%'
|
||
const svMarker = sv && sv.querySelector('span'); if (svMarker) { const sat = max ? d / max : 0; svMarker.style.left = (sat * 100) + '%'; svMarker.style.top = ((1 - max) * 100) + '%' }
|
||
const custom = runtime.el.querySelector('.iwb-editor-color-custom')
|
||
if (custom) {
|
||
custom.classList.toggle('active', !matchPreset)
|
||
const inp = custom.querySelector('input')
|
||
if (inp) inp.value = S.color
|
||
}
|
||
}
|
||
|
||
/** 画笔大小/硬度/透明曾经在侧栏也有一份,2026-11-04 起只保留工具选项栏一处,
|
||
* 这两个函数退化为「把值同步进选项栏」,保留名字是因为 tools/layers 还在调用。 */
|
||
function updateBrushUI() {
|
||
syncOptionBar()
|
||
}
|
||
|
||
export function updateBrushParamUI() {
|
||
syncOptionBar()
|
||
}
|
||
|
||
function updateFillUI() {
|
||
const b = runtime.el.querySelector('[data-action="toggleFill"]')
|
||
if (b) b.classList.toggle('active', !!S.rectFill)
|
||
}
|
||
|
||
/** 图层按钮可用态:有选中元素才可用 */
|
||
export function updateLayerUI() {
|
||
const hasSel = !!(S.selectedTextId || S.selectedShapeId || S.layers.some(l => l.id === S.selectedLayerId && l.id !== 'base' && !l.locked))
|
||
runtime.el.querySelectorAll('.iwb-editor-layer-btn').forEach(b => {
|
||
b.disabled = !hasSel
|
||
})
|
||
}
|
||
|
||
// ============ 便利版 UI:就地选项栏 / 状态栏 / 更多菜单 ============
|
||
|
||
const TOOL_NAMES = {
|
||
select: '选择 / 移动', marquee: '框选', lasso: '套索', brush: '画笔', eraser: '橡皮',
|
||
pen: '钢笔', text: '文字', rect: '矩形', circle: '圆形', arrow: '箭头',
|
||
picker: '吸管', hand: '抓手', crop: '裁剪'
|
||
}
|
||
|
||
const OPT_HINTS = {
|
||
crop: '裁剪栏在画布下方;裁剪与选区互斥,确认后可 Ctrl+Z 撤销',
|
||
select: '点击选中元素,拖拽移动,手柄缩放',
|
||
picker: '点击画布取色;选中形状/文字时取色直接改它的颜色,取完自动切回上一个工具',
|
||
hand: '拖拽平移画布;任意工具下按住空格也可以',
|
||
marquee: '拖出选区 → 操作条就在选区旁边',
|
||
lasso: '按住拖动画圈,松手闭合'
|
||
}
|
||
|
||
/** 滑杆 + 数字框共用同一 data-opt,两条输入路径都写回 S */
|
||
function rangeOpt(key, label, min, max, value, unit) {
|
||
return `<span class="iwb-opt-label">${label}</span>
|
||
<input type="range" class="iwb-opt-range" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">
|
||
<input type="number" class="iwb-opt-num" data-opt="${key}" min="${min}" max="${max}" step="1" value="${value}">${unit ? `<span class="iwb-opt-unit">${unit}</span>` : ''}`
|
||
}
|
||
|
||
/** 快捷值圆点(用户裁定 2026-11-04:笔刷大小/矢量描边都要推荐值,跟侧栏快捷点同款交互) */
|
||
function presetDots(key, values) {
|
||
return `<span class="iwb-opt-dots">${values.map(v =>
|
||
`<button type="button" class="iwb-opt-dot" data-opt-preset="${key}" data-value="${v}" title="${v}"><i></i></button>`).join('')}</span>`
|
||
}
|
||
|
||
/** 裁剪参数行(用户裁定 2026-11-04:从画布下方浮窗搬进选项栏;Enter 确认 / Esc 取消) */
|
||
function cropOptionHTML() {
|
||
const c = S.cropConstraint
|
||
const sizeOn = c.type === 'size'
|
||
return `<span class="iwb-opt-label">比例</span>
|
||
<button type="button" class="iwb-editor-constraint-btn${c.type === 'free' ? ' active' : ''}" data-ratio="free">自由</button>
|
||
<button type="button" class="iwb-editor-constraint-btn" data-ratio="1:1">1:1</button>
|
||
<button type="button" class="iwb-editor-constraint-btn" data-ratio="4:3">4:3</button>
|
||
<button type="button" class="iwb-editor-constraint-btn" data-ratio="3:4">3:4</button>
|
||
<button type="button" class="iwb-editor-constraint-btn" data-ratio="16:9">16:9</button>
|
||
<button type="button" class="iwb-editor-constraint-btn" data-ratio="9:16">9:16</button>
|
||
<span class="iwb-opt-label">尺寸</span>
|
||
<input type="number" class="iwb-editor-size-input iwb-editor-size-w" min="1" placeholder="宽" value="800">
|
||
<span class="iwb-opt-unit">×</span>
|
||
<input type="number" class="iwb-editor-size-input iwb-editor-size-h" min="1" placeholder="高" value="800">
|
||
<button type="button" class="iwb-editor-constraint-btn iwb-editor-size-toggle" data-action="toggleSizeConstraint" aria-pressed="${sizeOn}">启用尺寸</button>
|
||
<button type="button" class="iwb-editor-constraint-btn iwb-editor-size-apply" data-action="applySize">应用</button>
|
||
<span class="iwb-editor-crop-info">--</span>
|
||
<button type="button" class="iwb-editor-crop-confirm" data-action="confirmCrop" title="Enter">✓ 确认</button>
|
||
<button type="button" class="iwb-editor-crop-cancel" data-action="cancelCrop" title="Esc">✗ 取消</button>
|
||
<span class="iwb-opt-hint">拖出裁剪框;Enter 确认 · Esc 取消;裁剪后可 Ctrl+Z</span>`
|
||
}
|
||
|
||
/** 描边/实心切换按钮组:owner 区分两套默认值(rect=矩形/圆,pen=钢笔)。
|
||
* 钢笔只在闭合路径上才有填充面积,但开关本身一直可点,便于先选后画。 */
|
||
function fillStyleHTML(owner) {
|
||
const fill = owner === 'pen' ? S.penFill : S.rectFill
|
||
return `<span class="iwb-opt-label">样式</span>
|
||
<button class="iwb-opt-btn${fill ? '' : ' active'}" data-opt-toggle="stroke" data-fill-owner="${owner}" data-value="stroke" title="描边 (Shift+X 切换)">描边</button>
|
||
<button class="iwb-opt-btn${fill ? ' active' : ''}" data-opt-toggle="fill" data-fill-owner="${owner}" data-value="fill" title="实心 (Shift+X 切换)">实心</button>`
|
||
}
|
||
|
||
const SHAPE_NAMES = { rect: '矩形', circle: '圆形', arrow: '箭头', pen: '钢笔路径' }
|
||
|
||
/** 选择工具:只有选中了元素才出该元素的参数。
|
||
* 用户裁定 2026-11-04:选中矩形/钢笔后要能就地切描边/实心、改描边粗细,
|
||
* 不必再切回绘制工具 —— 所以这里复用绘制工具同一套控件与写回路径。 */
|
||
/** 选区命令(全选/反选/取消):用户裁定 2026-11-04 晚 —— 不放竖工具条,
|
||
* 启用「选择」工具时显示在工具选项栏里(data-more 走 bindLiteUI 的根级委托)。 */
|
||
const SELCMD_SVGS = {
|
||
all: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="3 2"><rect x="3.5" y="3.5" width="17" height="17" rx="1"/></svg>',
|
||
invert: '<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.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><rect x="8" y="8" width="8" height="8" rx="1" fill="currentColor" stroke="none"/></svg>',
|
||
none: '<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.5" y="3.5" width="17" height="17" rx="1" stroke-dasharray="3 2"/><line x1="4" y1="20" x2="20" y2="4"/></svg>'
|
||
}
|
||
const selCmdHTML = () =>
|
||
`<span class="iwb-opt-sep"></span>
|
||
<button class="iwb-opt-selcmd" data-more="sel.all" title="全选 (Ctrl+A)">${SELCMD_SVGS.all}</button>
|
||
<button class="iwb-opt-selcmd" data-more="sel.invert" title="反选 (Ctrl+Shift+I)">${SELCMD_SVGS.invert}</button>
|
||
<button class="iwb-opt-selcmd" data-more="sel.none" title="取消选区 (Esc / Ctrl+D)">${SELCMD_SVGS.none}</button>`
|
||
|
||
function selectOptionHTML() {
|
||
const sh = getSelectedShape()
|
||
if (sh) {
|
||
const t = sh.type
|
||
if (t === 'rect' || t === 'circle' || t === 'pen' || t === 'arrow') {
|
||
const owner = t === 'pen' ? 'pen' : 'rect'
|
||
const lw = Math.max(1, Math.round(sh.lw || S.shapeLineWidth))
|
||
return `<span class="iwb-opt-current">已选中:${SHAPE_NAMES[t] || t}</span>`
|
||
+ rangeOpt('shapeLineWidth', '线宽', 1, 60, lw, '')
|
||
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
|
||
+ (t === 'arrow' ? '' : fillStyleHTML(owner))
|
||
+ (t === 'pen' && !sh.closed
|
||
? '<span class="iwb-opt-hint">这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充</span>'
|
||
: '')
|
||
+ selCmdHTML()
|
||
}
|
||
}
|
||
const text = getSelectedText()
|
||
if (text) {
|
||
return `<span class="iwb-opt-current">已选中:文字</span>`
|
||
+ rangeOpt('textSize', '字号', 8, 400, Math.round(text.fontSize || S.textSize), 'px')
|
||
+ '<span class="iwb-opt-hint">双击文字改内容,拖动移动,手柄缩放</span>'
|
||
+ selCmdHTML()
|
||
}
|
||
return `<span class="iwb-opt-current">当前工具:选择 / 移动</span>
|
||
<span class="iwb-opt-hint">点中矩形/圆形/钢笔/文字后,这里会出现它的描边、实心与粗细</span>`
|
||
+ selCmdHTML()
|
||
}
|
||
|
||
/** 每个工具只露最常用的 2–4 个参数,全部直接写回 S(右侧参数面板同步) */
|
||
function optionBarHTML(tool) {
|
||
if (tool === 'crop') return cropOptionHTML()
|
||
if (tool === 'select') return selectOptionHTML()
|
||
if (tool === 'brush' || tool === 'eraser') {
|
||
return rangeOpt('brushSize', '大小', 1, 300, S.brushSize, '')
|
||
+ presetDots('brushSize', [2, 4, 8, 12])
|
||
+ `<span class="iwb-opt-label">硬度</span>
|
||
<input type="range" class="iwb-opt-range iwb-opt-range-wide" data-opt="brushHardness" min="0" max="100" step="1" value="${S.brushHardness}">
|
||
<span class="iwb-opt-val" data-opt-val="brushHardness">${S.brushHardness}</span>
|
||
<span class="iwb-opt-label">透明</span>
|
||
<input type="range" class="iwb-opt-range" data-opt="brushOpacity" min="5" max="100" step="1" value="${Math.round(S.brushOpacity * 100)}">
|
||
<span class="iwb-opt-val" data-opt-val="brushOpacity">${Math.round(S.brushOpacity * 100)}%</span>`
|
||
+ presetDots('brushHardness', [0, 25, 50, 75, 100])
|
||
}
|
||
if (tool === 'rect' || tool === 'circle') {
|
||
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
|
||
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
|
||
+ fillStyleHTML('rect')
|
||
}
|
||
if (tool === 'arrow') {
|
||
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
|
||
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
|
||
+ '<span class="iwb-opt-hint">拖出箭头,松手完成</span>'
|
||
}
|
||
if (tool === 'pen') {
|
||
return rangeOpt('shapeLineWidth', '线宽', 1, 60, S.shapeLineWidth, '')
|
||
+ presetDots('shapeLineWidth', [1, 2, 3, 6, 10, 16, 24])
|
||
+ fillStyleHTML('pen')
|
||
+ '<span class="iwb-opt-hint">逐点点击,点回起点闭合;闭合后可切换描边/实心</span>'
|
||
}
|
||
if (tool === 'text') {
|
||
return rangeOpt('textSize', '字号', 8, 400, S.textSize, 'px')
|
||
+ '<span class="iwb-opt-hint">点画布输入文字,Enter 确认</span>'
|
||
}
|
||
if (tool === 'marquee') {
|
||
return `<span class="iwb-opt-label">形状</span>
|
||
<button class="iwb-opt-btn${S.selectionKind === 'rect' ? ' active' : ''}" data-opt="shape" data-value="rect">矩形</button>
|
||
<button class="iwb-opt-btn${S.selectionKind === 'ellipse' ? ' active' : ''}" data-opt="shape" data-value="ellipse">椭圆</button>
|
||
<label class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</label>
|
||
<span class="iwb-opt-hint">${OPT_HINTS.marquee}</span>`
|
||
}
|
||
if (tool === 'lasso') {
|
||
return `<span class="iwb-opt-label">羽化 <input type="number" class="iwb-opt-num" data-opt="feather" min="0" max="20" step="1" value="${S.selectionFeather}"> px</span>
|
||
<span class="iwb-opt-hint">${OPT_HINTS.lasso}</span>`
|
||
}
|
||
return `<span class="iwb-opt-current">当前工具:${TOOL_NAMES[tool] || tool}</span>
|
||
<span class="iwb-opt-hint">${OPT_HINTS[tool] || '选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层'}</span>`
|
||
}
|
||
|
||
export function renderOptionBar(force) {
|
||
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
|
||
if (!body) return
|
||
// 工具没变就只同步数值:renderAll 每次操作都会走到这里,全量重建 innerHTML
|
||
// 会打断正在拖的滑杆和正在输入的数字框(静态审查 P2-11)。
|
||
// 签名里带上选中对象 id:选择工具下换选一个形状,参数区必须整体重建。
|
||
const sig = S.tool + '|' + (S.selectedShapeId || '') + '|' + (S.selectedTextId || '')
|
||
if (!force && body.dataset.sig === sig) { syncOptionBar(); return }
|
||
body.dataset.sig = sig
|
||
body.dataset.tool = S.tool
|
||
body.innerHTML = optionBarHTML(S.tool)
|
||
if (S.tool === 'crop') updateCropInfo() // 重渲染后裁剪尺寸摘要要立即就位
|
||
syncOptionBar()
|
||
}
|
||
|
||
/** 只更新值与选中态,不重建 DOM —— 保证拖拽中的控件与输入焦点不被抢 */
|
||
export function syncOptionBar() {
|
||
const body = runtime.el && runtime.el.querySelector('.iwb-editor-optionbar-body')
|
||
if (!body) return
|
||
// 选择工具下参数显示的是「选中对象自己的值」,不是新建默认值
|
||
const selShape = S.tool === 'select' ? getSelectedShape() : null
|
||
const selText = S.tool === 'select' ? getSelectedText() : null
|
||
const val = (key) => {
|
||
if (key === 'brushSize') return S.brushSize
|
||
if (key === 'brushHardness') return S.brushHardness
|
||
if (key === 'brushOpacity') return Math.round(S.brushOpacity * 100)
|
||
if (key === 'shapeLineWidth') return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth
|
||
if (key === 'textSize') return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize
|
||
if (key === 'feather') return S.selectionFeather
|
||
return ''
|
||
}
|
||
body.querySelectorAll('input[data-opt]').forEach(el => {
|
||
if (document.activeElement === el) return // 正在拖/正在输入的不要被覆盖
|
||
const v = val(el.dataset.opt)
|
||
if (String(el.value) !== String(v)) el.value = v
|
||
})
|
||
body.querySelectorAll('[data-opt-val]').forEach(el => {
|
||
const v = val(el.dataset.optVal)
|
||
el.textContent = el.dataset.optVal === 'brushOpacity' ? v + '%' : v
|
||
})
|
||
body.querySelectorAll('[data-opt="shape"]').forEach(btn => {
|
||
btn.classList.toggle('active', S.selectionKind === btn.dataset.value)
|
||
})
|
||
body.querySelectorAll('[data-opt-toggle]').forEach(btn => {
|
||
const owner = btn.dataset.fillOwner === 'pen' ? 'pen' : 'rect'
|
||
let cur = owner === 'pen' ? S.penFill : S.rectFill
|
||
// 选中态以对象自身的 fill 为准,否则按钮显示会和画面相反
|
||
if (selShape && (owner === 'pen' ? selShape.type === 'pen' : (selShape.type === 'rect' || selShape.type === 'circle'))) {
|
||
cur = !!selShape.fill
|
||
}
|
||
btn.classList.toggle('active', !!cur === (btn.dataset.value === 'fill'))
|
||
})
|
||
}
|
||
|
||
/** 状态栏:缩放 / 尺寸 / 光标 / 选区 / 当前层 / 工具 */
|
||
export function updateStatusbar() {
|
||
if (!runtime.el) return
|
||
const put = (sel, text) => {
|
||
const el = runtime.el.querySelector(sel)
|
||
if (el && el.textContent !== text) el.textContent = text
|
||
}
|
||
put('.iwb-editor-status-zoom', Math.round(S.zoom * 100) + '%')
|
||
put('.iwb-editor-status-size', S.imgW + '×' + S.imgH)
|
||
const p = S.lastPos
|
||
put('.iwb-editor-status-pos', p ? ('x ' + Math.round(p.x) + ' y ' + Math.round(p.y)) : 'x — y —')
|
||
const sel = S.selection && S.selection.active ? S.selection : null
|
||
put('.iwb-editor-status-sel', sel
|
||
? '选区 ' + Math.round(sel.bbox.w) + '×' + Math.round(sel.bbox.h) + (sel.feather ? ' · 羽化 ' + sel.feather : '') + (sel.inverted ? ' · 反选' : '')
|
||
: '无选区')
|
||
const layer = S.layers.find(l => l.id === S.activeLayerId)
|
||
put('.iwb-editor-status-layer', '当前层:' + (layer ? layer.name : '—'))
|
||
put('.iwb-editor-status-tool', TOOL_NAMES[S.tool] || S.tool)
|
||
}
|
||
|
||
// ---- 选项栏参数写回:单一真源是 S,右侧参数面板与画布随后同步 ----
|
||
|
||
let lwSnapDone = false
|
||
let textSnapDone = false
|
||
|
||
/** 线宽也作用到当前选中的形状:拖动中只重绘,松手才记一步历史 */
|
||
function applyShapeLineWidth(committed) {
|
||
const sh = getSelectedShape()
|
||
if (!sh || sh.locked) { lwSnapDone = false; return }
|
||
if (committed || !lwSnapDone) { saveSnapshot('线宽'); lwSnapDone = true }
|
||
sh.lw = S.shapeLineWidth
|
||
renderObjects()
|
||
if (committed) lwSnapDone = false
|
||
}
|
||
|
||
/** 字号也作用到当前选中的文字 */
|
||
function applyTextSize(committed) {
|
||
const t = getSelectedText()
|
||
if (!t || t.locked) { textSnapDone = false; return }
|
||
if (committed || !textSnapDone) { saveSnapshot('字号'); textSnapDone = true }
|
||
t.fontSize = S.textSize
|
||
renderObjects()
|
||
if (committed) textSnapDone = false
|
||
}
|
||
|
||
/** 形状描边/实心:既改下次新建的默认值,也改当前选中的那个。
|
||
* owner='rect' 作用于矩形/圆,owner='pen' 作用于钢笔闭合路径。 */
|
||
function setShapeFill(fill, owner) {
|
||
const isPen = owner === 'pen'
|
||
if (isPen) S.penFill = !!fill
|
||
else S.rectFill = !!fill
|
||
updateFillUI()
|
||
syncOptionBar()
|
||
const sh = getSelectedShape()
|
||
const types = isPen ? ['pen'] : ['rect', 'circle']
|
||
if (sh && types.indexOf(sh.type) >= 0 && !sh.locked) {
|
||
saveSnapshot('填充')
|
||
// 未闭合的钢笔路径没有可填区域:保持描边,不动视觉结果
|
||
sh.fill = isPen ? (!!S.penFill && !!sh.closed) : !!S.rectFill
|
||
renderObjects()
|
||
// 对象的 fill 更新在 sync 之后,选择工具下按钮的激活态要再刷一次
|
||
syncOptionBar()
|
||
}
|
||
}
|
||
|
||
function setOptionFromControl(el, committed) {
|
||
const key = el && el.dataset ? el.dataset.opt : ''
|
||
if (!key) return
|
||
const n = Math.round(Number(el.value))
|
||
const safe = Number.isFinite(n) ? n : 0
|
||
if (key === 'brushSize') {
|
||
S.brushSize = clamp(safe || 1, 1, 300)
|
||
updateBrushUI()
|
||
updateBrushParamUI()
|
||
refreshBrushRing()
|
||
} else if (key === 'brushHardness') {
|
||
S.brushHardness = clamp(safe, 0, 100)
|
||
updateBrushParamUI()
|
||
} else if (key === 'brushOpacity') {
|
||
S.brushOpacity = clamp(safe || 100, 5, 100) / 100
|
||
updateBrushParamUI()
|
||
if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity
|
||
} else if (key === 'shapeLineWidth') {
|
||
S.shapeLineWidth = clamp(safe || 1, 1, 60)
|
||
applyShapeLineWidth(committed)
|
||
} else if (key === 'textSize') {
|
||
S.textSize = clamp(safe || 32, 8, 400)
|
||
applyTextSize(committed)
|
||
} else if (key === 'feather') {
|
||
S.selectionFeather = clamp(safe, 0, 20)
|
||
if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather
|
||
updateStatusbar()
|
||
}
|
||
syncOptionBar()
|
||
}
|
||
|
||
/** 收起 / 展开左右侧栏(顶栏按钮与 PS 习惯的 Tab 键共用,状态写回 settings) */
|
||
export function togglePanelsCollapsed() {
|
||
const root = runtime.el
|
||
if (!root) return
|
||
const collapsed = !root.classList.contains('panels-collapsed')
|
||
root.classList.toggle('panels-collapsed', collapsed)
|
||
const st = S.callbacks && S.callbacks.settings
|
||
if (st && typeof st.set === 'function') {
|
||
try { st.set('panelsCollapsed', collapsed) } catch (err) { /* ignore */ }
|
||
}
|
||
toast(collapsed ? '侧栏已收起' : '侧栏已展开', 'info')
|
||
}
|
||
|
||
/** 顶栏命令带 / 面板收起 / 选项栏控件:只绑定一次,DOM 重绘不丢事件(委托) */
|
||
export function bindLiteUI() {
|
||
const root = runtime.el
|
||
if (!root || root.dataset.liteBound === '1') return
|
||
root.dataset.liteBound = '1'
|
||
|
||
const closeMenus = () => {
|
||
const panel = root.querySelector('.iwb-editor-export-settings')
|
||
if (panel) panel.classList.remove('open')
|
||
const toggle = root.querySelector('[data-action="toggleExportSettings"]')
|
||
if (toggle) toggle.setAttribute('aria-expanded', 'false')
|
||
}
|
||
|
||
// 选区命令(全选/反选/取消)在「选择」工具的选项栏里,与竖工具条时代一样走根级事件委托:
|
||
// 三个按钮不切换工具,只调命令层(与快捷键、右键菜单同一条路径)。
|
||
root.addEventListener('click', (e) => {
|
||
// 快速效果(侧栏):点一下即应用,目标层与撤销由 effects.js 负责
|
||
const fxBtn = e.target.closest('[data-fx]')
|
||
if (fxBtn) {
|
||
e.stopPropagation()
|
||
applyQuickEffect(fxBtn.dataset.fx)
|
||
return
|
||
}
|
||
const btn = e.target.closest('[data-more]')
|
||
if (!btn) return
|
||
e.stopPropagation()
|
||
const key = btn.dataset.more
|
||
if (key && key.indexOf('sel.') === 0) runCommand(key)
|
||
else if (key === 'addBlankLayer') addBlankLayer()
|
||
else if (key === 'zoomFit') setZoomFit()
|
||
else if (key === 'reset') restoreAll()
|
||
})
|
||
|
||
root.querySelectorAll('[data-action="togglePanels"]').forEach(btn => {
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', (e) => {
|
||
e.stopPropagation()
|
||
togglePanelsCollapsed()
|
||
closeMenus()
|
||
})
|
||
})
|
||
|
||
const body = root.querySelector('.iwb-editor-optionbar-body')
|
||
if (body) {
|
||
body.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
// 滑杆拖动中(input)与松手/失焦(change)走同一条写回路径,
|
||
// committed 只决定「要不要顺手记一步历史」,不影响参数生效。
|
||
body.addEventListener('input', (e) => setOptionFromControl(e.target, false))
|
||
body.addEventListener('change', (e) => setOptionFromControl(e.target, true))
|
||
body.addEventListener('click', (e) => {
|
||
const shapeBtn = e.target.closest('[data-opt="shape"]')
|
||
if (shapeBtn) {
|
||
e.stopPropagation()
|
||
S.selectionKind = shapeBtn.dataset.value === 'ellipse' ? 'ellipse' : 'rect'
|
||
syncOptionBar()
|
||
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
|
||
return
|
||
}
|
||
const toggle = e.target.closest('[data-opt-toggle]')
|
||
if (toggle) {
|
||
e.stopPropagation()
|
||
setShapeFill(toggle.dataset.value === 'fill', toggle.dataset.fillOwner)
|
||
return
|
||
}
|
||
// 快捷值圆点:笔刷大小 / 矢量描边(用户裁定进选项栏)
|
||
const dot = e.target.closest('[data-opt-preset]')
|
||
if (dot) {
|
||
e.stopPropagation()
|
||
setOptionFromControl({ dataset: { opt: dot.dataset.optPreset }, value: dot.dataset.value }, true)
|
||
return
|
||
}
|
||
// ---- 裁剪控件(从画布下方浮窗搬进选项栏,委托绑定防重渲染丢事件) ----
|
||
const ratioBtn = e.target.closest('[data-ratio]')
|
||
if (ratioBtn) {
|
||
e.stopPropagation()
|
||
const ratio = parseRatio(ratioBtn.dataset.ratio)
|
||
body.querySelectorAll('.iwb-editor-constraint-btn[data-ratio]').forEach(b => b.classList.toggle('active', b === ratioBtn))
|
||
setConstraint(ratio > 0 ? 'ratio' : 'free', ratio > 0 ? ratio : 0, 0, 0)
|
||
return
|
||
}
|
||
if (e.target.closest('[data-action="toggleSizeConstraint"]')) {
|
||
e.stopPropagation()
|
||
if (S.cropConstraint.type === 'size') { setConstraint('free', 0, 0, 0) }
|
||
else {
|
||
const w = parseInt(body.querySelector('.iwb-editor-size-w').value, 10)
|
||
const h = parseInt(body.querySelector('.iwb-editor-size-h').value, 10)
|
||
if (w > 0 && h > 0) {
|
||
body.querySelectorAll('.iwb-editor-constraint-btn[data-ratio]').forEach(b => b.classList.remove('active'))
|
||
setConstraint('size', w / h, w, h)
|
||
}
|
||
}
|
||
return
|
||
}
|
||
if (e.target.closest('[data-action="applySize"]')) {
|
||
e.stopPropagation()
|
||
const w = parseInt(body.querySelector('.iwb-editor-size-w').value, 10)
|
||
const h = parseInt(body.querySelector('.iwb-editor-size-h').value, 10)
|
||
if (w > 0 && h > 0) {
|
||
body.querySelectorAll('.iwb-editor-constraint-btn[data-ratio]').forEach(b => b.classList.remove('active'))
|
||
setConstraint('size', w / h, w, h)
|
||
}
|
||
return
|
||
}
|
||
if (e.target.closest('[data-action="confirmCrop"]')) { e.stopPropagation(); confirmCrop(); return }
|
||
if (e.target.closest('[data-action="cancelCrop"]')) { e.stopPropagation(); cancelCrop(); return }
|
||
})
|
||
}
|
||
|
||
// 点画布 / 面板其它地方收起输出设置下拉。必须用捕获阶段:modal 自身有个
|
||
// mousedown stopPropagation(阻止宿主抢事件),冒泡阶段收不到。
|
||
const modal = root.querySelector('.iwb-editor-modal') || root
|
||
modal.addEventListener('mousedown', (e) => {
|
||
if (!e.target.closest('.iwb-editor-export-settings-wrap')) closeMenus()
|
||
}, true)
|
||
}
|
||
|
||
// ============ 事件绑定 ============
|
||
/**
|
||
* 安全绑定:选择器找不到元素时只告警一次、不抛异常。
|
||
* 原实现是 querySelector(...).addEventListener 直接连写 —— DOM 里少一个元素
|
||
* 就会抛 TypeError 并中断**之后的所有绑定**,表现为"某个按钮突然全都不响应"。
|
||
*/
|
||
const warnedMissing = new Set()
|
||
function bindIf(selector, type, handler, root) {
|
||
const el = (root || runtime.el).querySelector(selector)
|
||
if (!el) {
|
||
if (!warnedMissing.has(selector)) {
|
||
warnedMissing.add(selector)
|
||
console.warn('[IWB编辑器] 未找到元素,跳过绑定:' + selector)
|
||
}
|
||
return null
|
||
}
|
||
el.addEventListener(type, handler)
|
||
return el
|
||
}
|
||
|
||
/** 同一个动作在顶栏/侧栏/面板都可能出现一个按钮(如「适应窗口」),全部绑上 */
|
||
function bindAll(selector, type, handler) {
|
||
const list = runtime.el.querySelectorAll(selector)
|
||
list.forEach(el => el.addEventListener(type, handler))
|
||
return list.length
|
||
}
|
||
|
||
export function bindEvents() {
|
||
bindToolButtons()
|
||
bindColorPanel()
|
||
bindColorPalette()
|
||
bindFillToggle()
|
||
bindLayerOrderButtons()
|
||
bindZoomButtons()
|
||
bindHistoryActions()
|
||
bindLayerAddActions()
|
||
bindExportActions()
|
||
bindWheelZoom()
|
||
bindTextInput()
|
||
bindGlobalListeners()
|
||
}
|
||
|
||
/** 工具条按钮:点击切换当前工具(选区命令按钮也借用 .iwb-editor-tool 样式,靠 data-tool 过滤掉) */
|
||
function bindToolButtons() {
|
||
// 工具
|
||
runtime.el.querySelectorAll('.iwb-editor-tool').forEach(btn => {
|
||
if (!btn.dataset.tool) return
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', () => setTool(btn.dataset.tool))
|
||
})
|
||
}
|
||
|
||
/** 关闭色板弹层;返回「关之前是开着的」,供 Esc 决定要不要吞掉这次按键 */
|
||
export function closeColorPop() {
|
||
const pop = runtime.el && runtime.el.querySelector('.iwb-editor-color-pop')
|
||
if (!pop || pop.hidden) return false
|
||
pop.hidden = true
|
||
const btn = runtime.el.querySelector('[data-action="toggleColorPop"]')
|
||
if (btn) { btn.classList.remove('active'); btn.setAttribute('aria-expanded', 'false') }
|
||
return true
|
||
}
|
||
|
||
/** 弹层定位:贴工具栏色点上方、左对齐;上方放不下翻到下方,左右夹在 modal 内。
|
||
* 坐标用「按钮矩形 − modal 矩形」算,弹层是 modal 的绝对定位子节点,
|
||
* 这样宿主页面有 transform 时也不会错位。 */
|
||
function positionColorPop() {
|
||
const pop = runtime.el && runtime.el.querySelector('.iwb-editor-color-pop')
|
||
const btn = runtime.el && runtime.el.querySelector('[data-action="toggleColorPop"]')
|
||
const modal = runtime.el && runtime.el.querySelector('.iwb-editor-modal')
|
||
if (!pop || !btn || !modal || pop.hidden) return
|
||
const mr = modal.getBoundingClientRect()
|
||
const br = btn.getBoundingClientRect()
|
||
const pr = pop.getBoundingClientRect()
|
||
let left = br.left - mr.left - 10
|
||
left = Math.min(Math.max(8, left), Math.max(8, mr.width - pr.width - 8))
|
||
let top = br.top - mr.top - pr.height - 10
|
||
if (top < 8) top = br.bottom - mr.top + 10
|
||
pop.style.left = Math.round(left) + 'px'
|
||
pop.style.top = Math.round(top) + 'px'
|
||
}
|
||
|
||
function toggleColorPop() {
|
||
const pop = runtime.el.querySelector('.iwb-editor-color-pop')
|
||
const btn = runtime.el.querySelector('[data-action="toggleColorPop"]')
|
||
if (!pop || !btn) return
|
||
if (pop.hidden) {
|
||
pop.hidden = false // 先显示再量:hidden 元素 getBoundingClientRect 全是 0
|
||
btn.classList.add('active')
|
||
btn.setAttribute('aria-expanded', 'true')
|
||
positionColorPop()
|
||
} else {
|
||
closeColorPop()
|
||
}
|
||
}
|
||
|
||
/** 色板弹层(v1.3):工具栏色点开关;hex/吸管/推荐色/调色器都在这一个弹层里 */
|
||
function bindColorPanel() {
|
||
const pop = runtime.el.querySelector('.iwb-editor-color-pop')
|
||
const colorBtn = runtime.el.querySelector('[data-action="toggleColorPop"]')
|
||
if (colorBtn) {
|
||
colorBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
colorBtn.addEventListener('click', (e) => { e.stopPropagation(); toggleColorPop() })
|
||
}
|
||
if (pop) {
|
||
pop.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
// 点外面关闭:必须用捕获阶段 —— 画布的 mousedown 会 preventDefault,
|
||
// 冒泡阶段拿不到「点了外面」这件事。
|
||
document.addEventListener('mousedown', (e) => {
|
||
if (!pop.hidden && !pop.contains(e.target) && !(colorBtn && colorBtn.contains(e.target))) closeColorPop()
|
||
}, true)
|
||
window.addEventListener('resize', positionColorPop)
|
||
}
|
||
|
||
// 独立颜色面板:颜色选择后同步当前工具颜色。
|
||
const setPanelColor = (color) => applyColorChange(color)
|
||
// 拖动取色期间只拍一次快照:applyColorChange 每改一次颜色都会 saveSnapshot,
|
||
// 在 SV 里拖一下会连拍几百张全画质 ImageData(4K 图直接吃掉几百 MB)。
|
||
// pointerdown 先拍(此时颜色还没变,快照是「改之前」),之后每步只改对象。
|
||
let dragSnapped = false
|
||
const hasColorTarget = () => {
|
||
const t = getSelectedText(), sh = getSelectedShape()
|
||
return !!((t && !t.locked) || (sh && !sh.locked))
|
||
}
|
||
const setDragColor = (color) => {
|
||
if (!dragSnapped) {
|
||
if (hasColorTarget()) { saveSnapshot(); dragSnapped = true }
|
||
}
|
||
applyColorChange(color, { skipHistory: true })
|
||
}
|
||
const panelHexInput = runtime.el.querySelector('.iwb-editor-color-hex-input')
|
||
if (panelHexInput) panelHexInput.addEventListener('change', () => { if (/^#[0-9a-f]{6}$/i.test(panelHexInput.value)) setPanelColor(panelHexInput.value) })
|
||
runtime.el.querySelectorAll('.iwb-editor-color-panel-swatch').forEach(btn => btn.addEventListener('click', (e) => { e.stopPropagation(); setPanelColor(btn.dataset.panelColor) }))
|
||
const palettePick = runtime.el.querySelector('[data-action="palettePick"]')
|
||
if (palettePick) {
|
||
palettePick.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
// 取色要回画布点,弹层必须先收起,否则它会挡住取样点
|
||
palettePick.addEventListener('click', () => { closeColorPop(); setTool('picker') })
|
||
}
|
||
const sv = runtime.el.querySelector('.iwb-color-sv')
|
||
const hue = runtime.el.querySelector('.iwb-color-hue')
|
||
const initHsv = (() => {
|
||
const { r, g, b } = hexToRgb(S.color)
|
||
const rr = r / 255, gg = g / 255, bb = b / 255
|
||
const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min
|
||
let h = 0
|
||
if (d) { if (max === rr) h = 60 * (((gg - bb) / d) % 6); else if (max === gg) h = 60 * ((bb - rr) / d + 2); else h = 60 * ((rr - gg) / d + 4) }
|
||
if (h < 0) h += 360
|
||
return { h, sat: max ? d / max : 0, val: max }
|
||
})()
|
||
let hueValue = initHsv.h
|
||
let satValue = initHsv.sat
|
||
let valValue = initHsv.val
|
||
const hsvToHex = (h, sat, val) => {
|
||
const c = val * sat, x = c * (1 - Math.abs((h / 60) % 2 - 1)), m = val - c
|
||
let r = 0, g = 0, b = 0
|
||
if (h < 60) { r = c; g = x } else if (h < 120) { r = x; g = c } else if (h < 180) { g = c; b = x } else if (h < 240) { g = x; b = c } else if (h < 300) { r = x; b = c } else { r = c; b = x }
|
||
return rgbToHex(Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255))
|
||
}
|
||
const pick = (target, e) => {
|
||
const r = target.getBoundingClientRect()
|
||
const x = clamp((e.clientX - r.left) / r.width, 0, 1)
|
||
const y = clamp((e.clientY - r.top) / r.height, 0, 1)
|
||
if (target === hue) hueValue = y * 360
|
||
else { satValue = x; valValue = 1 - y }
|
||
setDragColor(hsvToHex(hueValue, satValue, valValue))
|
||
}
|
||
// 推荐色 / hex / 吸管改色时,闭包里的 h/s/v 会过期(v1.3 修:以前点了绿色再拖 SV 会跳回红色)。
|
||
// 每次按下前从 S.color 重新同步;灰阶(d=0,如 #000)反推不出色相,就沿用旧色相。
|
||
const syncFromColor = () => {
|
||
const { r, g, b } = hexToRgb(S.color)
|
||
const rr = r / 255, gg = g / 255, bb = b / 255
|
||
const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min
|
||
if (d > 0) {
|
||
let h = 0
|
||
if (max === rr) h = 60 * (((gg - bb) / d) % 6)
|
||
else if (max === gg) h = 60 * ((bb - rr) / d + 2)
|
||
else h = 60 * ((rr - gg) / d + 4)
|
||
if (h < 0) h += 360
|
||
hueValue = h
|
||
}
|
||
satValue = max ? d / max : 0
|
||
valValue = max
|
||
}
|
||
const beginDrag = (target, e) => { syncFromColor(); dragSnapped = false; pick(target, e) }
|
||
if (sv) {
|
||
sv.addEventListener('pointerdown', e => { sv.setPointerCapture(e.pointerId); beginDrag(sv, e) })
|
||
sv.addEventListener('pointermove', e => { if (e.buttons) pick(sv, e) })
|
||
}
|
||
if (hue) {
|
||
hue.addEventListener('pointerdown', e => { beginDrag(hue, e) })
|
||
hue.addEventListener('pointermove', e => { if (e.buttons) pick(hue, e) })
|
||
}
|
||
}
|
||
|
||
/** 裁剪约束控件已迁入选项栏(bindLiteUI 的点击委托统一处理),旧的直连绑定移除。 */
|
||
|
||
/** 调色板色块与自定义取色 input */
|
||
function bindColorPalette() {
|
||
// 颜色
|
||
runtime.el.querySelectorAll('.iwb-editor-color[data-color]').forEach(s => {
|
||
s.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
s.addEventListener('click', () => applyColorChange(s.dataset.color))
|
||
})
|
||
|
||
const colorInput = runtime.el.querySelector('.iwb-editor-color-picker-input')
|
||
if (colorInput) {
|
||
colorInput.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
colorInput.addEventListener('input', () => applyColorChange(colorInput.value))
|
||
}
|
||
}
|
||
|
||
/** 实心矩形/圆形开关 */
|
||
function bindFillToggle() {
|
||
// 实心矩形开关
|
||
const fillBtn = runtime.el.querySelector('[data-action="toggleFill"]')
|
||
if (fillBtn) fillBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
fillBtn && fillBtn.addEventListener('click', () => {
|
||
S.rectFill = !S.rectFill
|
||
updateFillUI()
|
||
const sh = getSelectedShape()
|
||
if (sh && (sh.type === 'rect' || sh.type === 'circle') && (S.tool === 'rect' || S.tool === 'circle' || S.tool === 'select')) {
|
||
saveSnapshot()
|
||
sh.fill = S.rectFill
|
||
renderObjects()
|
||
}
|
||
})
|
||
}
|
||
|
||
/** 图层顺序调节按钮(上移/下移/置顶/置底) */
|
||
function bindLayerOrderButtons() {
|
||
// 图层顺序调节
|
||
runtime.el.querySelectorAll('.iwb-editor-layer-btn').forEach(btn => {
|
||
btn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
btn.addEventListener('click', () => moveLayer(btn.dataset.layer))
|
||
})
|
||
}
|
||
|
||
/** 缩放按钮:缩小 / 放大 / 适应窗口 */
|
||
function bindZoomButtons() {
|
||
// 缩放按钮
|
||
bindIf('[data-action="zoomOut"]', 'click', (e) => {
|
||
e.stopPropagation()
|
||
zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2)
|
||
})
|
||
bindIf('[data-action="zoomIn"]', 'click', (e) => {
|
||
e.stopPropagation()
|
||
zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2)
|
||
})
|
||
bindAll('[data-action="zoomFit"]', 'click', (e) => {
|
||
e.stopPropagation()
|
||
setZoomFit()
|
||
})
|
||
}
|
||
|
||
/** 撤销 / 重做 / 重置 / 复原 */
|
||
function bindHistoryActions() {
|
||
// 撤销/重做/重置/复原
|
||
const undoBtn = runtime.el.querySelector('[data-action="undo"]')
|
||
const redoBtn = runtime.el.querySelector('[data-action="redo"]')
|
||
const resetBtn = runtime.el.querySelector('[data-action="reset"]')
|
||
const restoreBtn = runtime.el.querySelector('[data-action="restore"]')
|
||
undoBtn && undoBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
redoBtn && redoBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
resetBtn && resetBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
restoreBtn && restoreBtn.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
undoBtn && undoBtn.addEventListener('click', undo)
|
||
redoBtn && redoBtn.addEventListener('click', redo)
|
||
resetBtn && resetBtn.addEventListener('click', resetDraw)
|
||
restoreBtn && restoreBtn.addEventListener('click', restoreOriginal)
|
||
}
|
||
|
||
/** 裁剪确认/取消已迁入选项栏(bindLiteUI 委托),旧直连绑定移除。 */
|
||
|
||
/** 添加位图图层(导入图片)与新建空白图层:顶栏与其它入口统一绑,取第一个会漏按钮 */
|
||
function bindLayerAddActions() {
|
||
// 添加位图图层(导入图片)
|
||
bindAll('[data-action="addBitmapLayer"]', 'mousedown', (e) => e.stopPropagation())
|
||
bindAll('[data-action="addBitmapLayer"]', 'click', () => {
|
||
const fileInput = document.createElement('input')
|
||
fileInput.type = 'file'
|
||
fileInput.accept = 'image/*'
|
||
fileInput.addEventListener('change', async () => {
|
||
const file = fileInput.files[0]
|
||
if (!file) return
|
||
const reader = new FileReader()
|
||
reader.onload = async () => {
|
||
try {
|
||
const img = await loadImage(reader.result)
|
||
addBitmapLayer(img)
|
||
} catch (err) {
|
||
console.error('[IWB编辑器] 导入图层失败:', err)
|
||
}
|
||
}
|
||
reader.readAsDataURL(file)
|
||
})
|
||
fileInput.click()
|
||
})
|
||
|
||
// 新建空白图层
|
||
bindAll('[data-action="addBlankLayer"]', 'mousedown', (e) => e.stopPropagation())
|
||
bindAll('[data-action="addBlankLayer"]', 'click', () => {
|
||
addBlankLayer()
|
||
})
|
||
|
||
// 图层合并(v1.6):⌘/Ctrl 点击图层多选后可合并;未多选时向下合并
|
||
bindAll('[data-action="mergeLayers"]', 'mousedown', (e) => e.stopPropagation())
|
||
bindAll('[data-action="mergeLayers"]', 'click', () => {
|
||
const r = mergeLayers()
|
||
toast(r.msg, r.ok ? 'success' : 'warn')
|
||
})
|
||
bindAll('[data-action="mergeVisible"]', 'mousedown', (e) => e.stopPropagation())
|
||
bindAll('[data-action="mergeVisible"]', 'click', () => {
|
||
const r = mergeVisibleLayers()
|
||
toast(r.msg, r.ok ? 'success' : 'warn')
|
||
})
|
||
}
|
||
|
||
/** 底部动作:关闭 / 作为新节点 / 替换(导出入口) */
|
||
function bindExportActions() {
|
||
// 底部
|
||
bindIf('[data-action="cancel"]', 'click', close)
|
||
bindIf('[data-action="download"]', 'click', () => exportResult('download'))
|
||
bindIf('[data-action="newNode"]', 'click', () => exportResult('newNode'))
|
||
bindIf('[data-action="replace"]', 'click', () => exportResult('replace'))
|
||
}
|
||
|
||
/** 滚轮缩放:绑定在画布容器上(非 passive,需要 preventDefault) */
|
||
function bindWheelZoom() {
|
||
// canvas 事件绑定到第一个位图图层(初始时还没有图层,延迟绑定)
|
||
// 实际在 setupCanvas 后调用 bindCanvasEvents
|
||
// 滚轮缩放
|
||
S.canvasWrap.addEventListener('wheel', onWheel, { passive: false })
|
||
}
|
||
|
||
/** 文字输入框:Enter 提交、Esc 取消 */
|
||
function bindTextInput() {
|
||
// 文字输入
|
||
const textInput = runtime.el.querySelector('.iwb-editor-text-input')
|
||
textInput && textInput.addEventListener('mousedown', (e) => e.stopPropagation())
|
||
textInput && textInput.addEventListener('keydown', (e) => {
|
||
e.stopPropagation()
|
||
if (e.key === 'Enter') { e.preventDefault(); commitTextInput() }
|
||
else if (e.key === 'Escape') { e.preventDefault(); hideTextInput() }
|
||
})
|
||
}
|
||
|
||
/** 全局监听:键盘快捷键、窗口失焦、剪贴板粘贴、modal 内阻止冒泡 */
|
||
function bindGlobalListeners() {
|
||
// 键盘快捷键
|
||
document.addEventListener('keydown', onKeydown, true)
|
||
document.addEventListener('keyup', onKeyup, true)
|
||
// 剪贴板粘贴(⌘/Ctrl+V):编辑器打开时把剪贴板里的图片贴为新图层
|
||
document.addEventListener('paste', onPaste, true)
|
||
|
||
// 窗口失焦
|
||
window.addEventListener('blur', () => {
|
||
if (S.spaceDown) { S.spaceDown = false; updateCursor() }
|
||
if (S.panning) { S.panning = false; S.panStart = null; updateCursor() }
|
||
S._shiftDown = false
|
||
// Alt 的 keyup 可能落在窗口外,兜底结束临时吸管,避免工具卡在 picker
|
||
endAltPicker()
|
||
})
|
||
|
||
// 阻止 modal 内部点击冒泡
|
||
bindIf('.iwb-editor-modal', 'mousedown', (e) => e.stopPropagation())
|
||
}
|
||
|
||
function commitPenPath() {
|
||
if (!S.penPath || S.penPath.pts.length < 2) { S.penPath = null; renderObjects(); return }
|
||
saveSnapshot()
|
||
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penFill && !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
|
||
// 路径落成即回 V 并选中(v1.5):连续画多条就再按一次 P;节点编辑仍走 V 下双击
|
||
S.shapeLayers.push(shape); S.penPath = null; renderObjects(); renderLayerPanel()
|
||
finishCreateTool('shape', shape.id)
|
||
}
|
||
|
||
/** 将 canvas 鼠标事件绑定到活跃图层 canvas(在 setupCanvas 后调用,仅绑定一次) */
|
||
export function bindCanvasEvents() {
|
||
if (S._canvasEventsBound) return
|
||
S._canvasEventsBound = true
|
||
// 所有位图图层 canvas 共享同一组事件处理器
|
||
// 使用事件委托:在 canvasStack 上监听
|
||
S.canvasStack.addEventListener('mousedown', onMouseDown)
|
||
S.canvasStack.addEventListener('mousemove', onMouseMove)
|
||
S.canvasStack.addEventListener('mousemove', onCanvasHover)
|
||
window.addEventListener('mouseup', onMouseUp)
|
||
S.canvasStack.addEventListener('contextmenu', (e) => {
|
||
e.preventDefault()
|
||
if (S.open && !S.placingImage) showSelectionContext(e)
|
||
})
|
||
S.canvasStack.addEventListener('mouseleave', () => {
|
||
if (S.placingImage) return
|
||
// 离开画布:笔刷环清掉,同时忘掉悬停点,免得调大小时把环画到旧位置
|
||
S.hoverPos = null
|
||
if ((S.tool === 'brush' || S.tool === 'eraser') && !S.isDrawing) clearToolRing()
|
||
if (S.tool === 'picker') hidePickerTip()
|
||
})
|
||
|
||
// 双击不再挂 dblclick:画布上它不可靠(选中重绘会换掉命中元素,浏览器干脆不派发)。
|
||
// 双击语义统一由 onMouseDown → isDoubleClick / onCanvasDoubleClick 处理,见文件上方。
|
||
}
|
||
|
||
// 裁剪手柄 hover 光标
|
||
const CROP_CURSORS = {
|
||
nw: 'nwse-resize', se: 'nwse-resize',
|
||
ne: 'nesw-resize', sw: 'nesw-resize',
|
||
n: 'ns-resize', s: 'ns-resize',
|
||
e: 'ew-resize', w: 'ew-resize'
|
||
}
|
||
|
||
// 同 MOUSE_DOWN_HANDLERS:依赖 function 声明提升,勿改成 const 箭头函数
|
||
/** 悬停分发表:各工具的光标与预览(编排器负责前置守卫与旋转手柄优先) */
|
||
const HOVER_HANDLERS = {
|
||
select: onHoverSelect,
|
||
marquee: onHoverCrosshair,
|
||
lasso: onHoverCrosshair,
|
||
picker: onHoverPicker,
|
||
hand: onHoverHand,
|
||
brush: onHoverBrushRing,
|
||
eraser: onHoverBrushRing,
|
||
crop: onHoverCrop,
|
||
text: onHoverText,
|
||
pen: onHoverCrosshair,
|
||
rect: onHoverShape,
|
||
arrow: onHoverShape,
|
||
circle: onHoverShape
|
||
}
|
||
|
||
function onCanvasHover(e) {
|
||
if (S.placingImage) return
|
||
if (S.panning || S.spaceDown) return
|
||
if (S.isDrawing || S.textDrag || S.shapeDrag) return
|
||
const p = getPos(e)
|
||
if (!S.lastPos || Math.abs(p.x - S.lastPos.x) > 0.5 || Math.abs(p.y - S.lastPos.y) > 0.5) {
|
||
S.lastPos = p
|
||
updateStatusbar()
|
||
}
|
||
S.hoverPos = p
|
||
if (isOverRotationHandle(p)) { S.drawCanvasCursor(ROT_CURSOR); return }
|
||
const handler = Object.prototype.hasOwnProperty.call(HOVER_HANDLERS, S.tool) ? HOVER_HANDLERS[S.tool] : null
|
||
if (handler) handler(p, e)
|
||
else S.drawCanvasCursor('crosshair')
|
||
}
|
||
|
||
/** 选择工具:文字/形状手柄缩放光标 > 命中对象的移动光标 > 默认光标 */
|
||
function onHoverSelect(p) {
|
||
const th = hitTextHandle(p)
|
||
if (th) { S.drawCanvasCursor((th === 'nw' || th === 'se') ? 'nwse-resize' : 'nesw-resize'); return }
|
||
const shh = hitShapeHandle(p)
|
||
if (shh) {
|
||
const sh = getSelectedShape()
|
||
if (sh && sh.type === 'rect' && CROP_CURSORS[shh]) S.drawCanvasCursor(CROP_CURSORS[shh])
|
||
else S.drawCanvasCursor('move')
|
||
return
|
||
}
|
||
S.drawCanvasCursor(hitAnyObject(p) ? 'move' : 'default')
|
||
}
|
||
|
||
/** 吸管:十字光标 + 实时取色气泡 */
|
||
function onHoverPicker(p, e) {
|
||
S.drawCanvasCursor('crosshair')
|
||
showPickerTip(e, sampleColor(p))
|
||
}
|
||
|
||
/** 抓手 */
|
||
function onHoverHand() {
|
||
S.drawCanvasCursor('grab')
|
||
}
|
||
|
||
/** 画笔/橡皮:隐藏系统光标,改画与笔刷等大的圆环 */
|
||
function onHoverBrushRing(p) {
|
||
S.drawCanvasCursor('none')
|
||
drawToolRing(p)
|
||
}
|
||
|
||
/** 裁剪:手柄光标 > 框内移动光标 > 十字 */
|
||
function onHoverCrop(p) {
|
||
if (S.cropRect) {
|
||
const h = hitCropHandle(p)
|
||
if (h && CROP_CURSORS[h]) { S.drawCanvasCursor(CROP_CURSORS[h]); return }
|
||
if (insideRect(p, S.cropRect)) { S.drawCanvasCursor('move'); return }
|
||
}
|
||
S.drawCanvasCursor('crosshair')
|
||
}
|
||
|
||
/** 文字:手柄缩放 > 命中文字的移动 > 文本输入光标 */
|
||
function onHoverText(p) {
|
||
const h = hitTextHandle(p)
|
||
if (h) { S.drawCanvasCursor((h === 'nw' || h === 'se') ? 'nwse-resize' : 'nesw-resize'); return }
|
||
S.drawCanvasCursor(hitTextLayer(p) ? 'move' : 'text')
|
||
}
|
||
|
||
/** 钢笔 */
|
||
function onHoverCrosshair() {
|
||
S.drawCanvasCursor('crosshair')
|
||
}
|
||
|
||
/** 矩形/圆形/箭头:选中矩形的手柄用裁剪系光标,其余为移动/十字 */
|
||
function onHoverShape(p) {
|
||
const h = hitShapeHandle(p)
|
||
if (h) {
|
||
const sh = getSelectedShape()
|
||
if (sh && sh.type === 'rect' && CROP_CURSORS[h]) S.drawCanvasCursor(CROP_CURSORS[h])
|
||
else S.drawCanvasCursor('move')
|
||
return
|
||
}
|
||
S.drawCanvasCursor('crosshair')
|
||
}
|
||
|
||
/**
|
||
* 是否处于「正在输入文字」态 —— 只对**文字内容**输入框为真。
|
||
*
|
||
* v1.2 修正:原来任何 INPUT 都算打字,于是在选项栏的数字框(羽化/线宽/字号)
|
||
* 里输完值后,Ctrl+A、Ctrl+J、Delete、Esc 全被吞掉,表现成「快捷键突然没反应」。
|
||
* 参数控件里带修饰键的组合、Delete 与 Esc 一律放行给画布;单个字符仍然正常输入。
|
||
*/
|
||
function isTyping(e) {
|
||
const t = e.target
|
||
if (!t) return false
|
||
if (t.tagName === 'TEXTAREA') return true
|
||
if (t.tagName !== 'INPUT') return false
|
||
const cls = t.classList
|
||
if (cls && (cls.contains('iwb-editor-text-input') || cls.contains('iwb-editor-color-hex-input'))) return true
|
||
// 以下是参数控件(数字框 / 滑杆)
|
||
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return false
|
||
if (e.key === 'Delete' || e.key === 'Escape') return false
|
||
return true
|
||
}
|
||
|
||
function onKeydown(e) {
|
||
if (!S.open) return
|
||
// 图片放置模式
|
||
if (S.placingImage) {
|
||
if (e.key === 'Enter') { e.preventDefault(); confirmImagePlacement(); return }
|
||
if (e.key === 'Escape') { e.preventDefault(); cancelImagePlacement(); return }
|
||
}
|
||
if (e.key === 'Shift') S._shiftDown = true
|
||
// PS:画笔 / 橡皮下按住 Alt 临时吸管(点击取色,松开 Alt 回到原工具)
|
||
if (e.key === 'Alt' && !e.ctrlKey && !e.metaKey) {
|
||
e.preventDefault() // 防 Windows 浏览器把单独 Alt 当作菜单栏激活
|
||
beginAltPicker()
|
||
return
|
||
}
|
||
if (e.key === 'Enter' && S.tool === 'pen' && S.penPath) { e.preventDefault(); commitPenPath(); return }
|
||
// 裁剪:Enter 确认 / Esc 取消(用户裁定,替代浮窗上的两个按钮 —— 按钮也保留在选项栏)
|
||
if (e.key === 'Enter' && S.tool === 'crop' && S.cropRect) { e.preventDefault(); confirmCrop(); return }
|
||
if (e.key === 'Escape') {
|
||
if (isTyping(e)) { hideTextInput(); return }
|
||
// 色板弹层先关:它是最上层的浮层,Esc 应该先收它
|
||
if (closeColorPop()) { e.preventDefault(); return }
|
||
// 裁剪优先:有裁剪框时 Esc 取消裁剪
|
||
if (S.tool === 'crop' && S.cropRect) { e.preventDefault(); cancelCrop(); return }
|
||
// 选区优先:Esc 一步取消,不进菜单
|
||
if (S.marquee || S.lassoPts || (S.selection && S.selection.active)) { e.preventDefault(); clearMarquee(); return }
|
||
if (S.penPath) { e.preventDefault(); S.penPath = null; renderObjects(); return }
|
||
if (getPenEditingShape()) { e.preventDefault(); exitPenEdit(); return }
|
||
if (S.selectedLayerId || S.selectedTextId || S.selectedShapeId || S.bitmapDrag || S.textDrag || S.shapeDrag) {
|
||
e.preventDefault()
|
||
clearSelection()
|
||
renderObjects()
|
||
renderLayerPanel()
|
||
}
|
||
return
|
||
}
|
||
if (isTyping(e)) return
|
||
|
||
const mod = e.ctrlKey || e.metaKey
|
||
const key = String(e.key || '').toLowerCase()
|
||
|
||
// ================= PS 同款快捷键 =================
|
||
// 无修饰键:工具(V 移动 / M 选框 / L 套索 / B 画笔 / E 橡皮 / P 钢笔 / T 文字 / U 形状 / C 裁剪 / I 吸管 / H 抓手)
|
||
// 数字键 1–0 的老映射已按 PS 习惯移除(PS 里数字键是图层不透明度)。
|
||
const letterTools = {
|
||
v: 'select', m: 'marquee', l: 'lasso', b: 'brush', e: 'eraser', p: 'pen',
|
||
t: 'text', u: 'rect', c: 'crop', i: 'picker', h: 'hand'
|
||
}
|
||
if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(letterTools, key)) {
|
||
e.preventDefault()
|
||
if (e.shiftKey && key === 'u') {
|
||
// PS: Shift+U 在同类形状工具间循环
|
||
const cycle = { rect: 'circle', circle: 'arrow', arrow: 'rect' }
|
||
setTool(cycle[S.tool] || 'rect')
|
||
} else if (e.shiftKey && key === 'm') {
|
||
// PS: Shift+M 在矩形/椭圆选框间切换
|
||
S.selectionKind = S.selectionKind === 'ellipse' ? 'rect' : 'ellipse'
|
||
setTool('marquee')
|
||
toast('选区形状:' + (S.selectionKind === 'ellipse' ? '椭圆' : '矩形'), 'info')
|
||
renderOptionBar(true)
|
||
} else {
|
||
setTool(letterTools[key])
|
||
}
|
||
return
|
||
}
|
||
if (!mod && !e.altKey && key === 'tab') {
|
||
e.preventDefault()
|
||
togglePanelsCollapsed()
|
||
return
|
||
}
|
||
|
||
// PS 风格:Shift+X 切换选中形状的 描边/实心(与选项栏按钮共用 setShapeFill)
|
||
if (!mod && e.shiftKey && key === 'x') {
|
||
const sh = getSelectedShape()
|
||
if (sh && !sh.locked) {
|
||
e.preventDefault()
|
||
if (sh.type === 'arrow') { toast('箭头没有实心样式', 'info'); return }
|
||
setShapeFill(!sh.fill, sh.type === 'pen' ? 'pen' : 'rect')
|
||
}
|
||
return
|
||
}
|
||
|
||
// PS:] 增大 / [ 减小画笔大小(画笔与橡皮共用,光标环即时反馈)
|
||
// 同时匹配 e.code(BracketLeft/Right):中文输入法下 e.key 会变成「【」「】」,只看 e.key 会失灵
|
||
const isBracket = e.key === '[' || e.key === ']' || e.code === 'BracketLeft' || e.code === 'BracketRight'
|
||
if (!mod && !e.altKey && isBracket) {
|
||
e.preventDefault()
|
||
const step = S.brushSize >= 64 ? 8 : S.brushSize >= 24 ? 4 : S.brushSize >= 8 ? 2 : 1
|
||
S.brushSize = clamp(S.brushSize + (e.key === ']' ? step : -step), 1, 300)
|
||
syncOptionBar()
|
||
updateCursor()
|
||
refreshBrushRing()
|
||
return
|
||
}
|
||
|
||
// 视图:Ctrl+0 适应窗口 / Ctrl+1 100% / Ctrl+± 缩放(PS 习惯)
|
||
if (mod && !e.shiftKey && e.key === '0') { e.preventDefault(); setZoomFit(); return }
|
||
if (mod && !e.shiftKey && e.key === '1') { e.preventDefault(); setZoomActual(); return }
|
||
if (mod && (e.key === '+' || e.key === '=')) {
|
||
e.preventDefault()
|
||
zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2)
|
||
return
|
||
}
|
||
if (mod && e.key === '-') {
|
||
e.preventDefault()
|
||
zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2)
|
||
return
|
||
}
|
||
|
||
// ---- 选区快捷键:与浮动条 / 右键菜单共用同一命令层 ----
|
||
if (mod && key === 'a') { e.preventDefault(); runCommand('sel.all'); return }
|
||
if (mod && e.shiftKey && key === 'i') { e.preventDefault(); runCommand('sel.invert'); return }
|
||
if (mod && key === 'd') { e.preventDefault(); runCommand('sel.none'); return }
|
||
if (mod && key === 'j') { e.preventDefault(); runCommand('sel.copy'); return }
|
||
if (mod && key === 'x' && S.selection && S.selection.active) { e.preventDefault(); runCommand('sel.cut'); return }
|
||
|
||
// 图层合并(PS 习惯):Ctrl+E 合并(多选优先,否则向下合并)/ Ctrl+Shift+E 合并可见
|
||
if (mod && key === 'e') {
|
||
e.preventDefault()
|
||
const r = e.shiftKey ? mergeVisibleLayers() : mergeLayers()
|
||
toast(r.msg, r.ok ? 'success' : 'warn')
|
||
return
|
||
}
|
||
|
||
// 文件类:Ctrl+Shift+N 新建图层 / Ctrl+O 导入图片 / Ctrl+S 导出下载
|
||
if (mod && e.shiftKey && key === 'n') {
|
||
e.preventDefault()
|
||
addBlankLayer()
|
||
return
|
||
}
|
||
if (mod && !e.shiftKey && key === 'o') {
|
||
e.preventDefault()
|
||
const b = runtime.el && runtime.el.querySelector('[data-action="addBitmapLayer"]')
|
||
if (b) b.click()
|
||
return
|
||
}
|
||
if (mod && key === 's') {
|
||
e.preventDefault()
|
||
const b = runtime.el && runtime.el.querySelector('[data-action="download"]')
|
||
if (b) b.click()
|
||
return
|
||
}
|
||
|
||
if (e.key === 'Delete' || e.key === 'Backspace') {
|
||
// 有选区且没有选中矢量对象:只清当前层(用户裁定),不走「删对象」
|
||
if (S.selection && S.selection.active && !S.selectedTextId && !S.selectedShapeId) {
|
||
e.preventDefault()
|
||
runCommand('sel.delete')
|
||
return
|
||
}
|
||
if (S.selectedTextId) { e.preventDefault(); deleteSelectedText(); renderLayerPanel(); return }
|
||
if (S.selectedShapeId) { e.preventDefault(); deleteSelectedShape(); renderLayerPanel(); return }
|
||
// PS 习惯:选中位图层(非原图)时 Delete 直接删除该图层
|
||
if (S.selectedLayerId && S.selectedLayerId !== 'base') {
|
||
e.preventDefault()
|
||
deleteLayer(S.selectedLayerId)
|
||
renderLayerPanel()
|
||
return
|
||
}
|
||
}
|
||
if (e.code === 'Space') {
|
||
e.preventDefault()
|
||
if (!S.spaceDown) { S.spaceDown = true; updateCursor() }
|
||
return
|
||
}
|
||
// ---- 图层快捷键(PS 同款,统一用 e.code 匹配防中文输入法吞键)----
|
||
// Ctrl+] / Ctrl+[ 上移/下移一层;Ctrl+Shift+] / Ctrl+Shift+[ 置顶/置底;
|
||
// Alt+] / Alt+[ 向上/向下选择图层(Mac 上 Cmd+]/[ 被浏览器前进/后退占用,用 Ctrl)
|
||
if (e.code === 'BracketLeft' || e.code === 'BracketRight') {
|
||
const up = e.code === 'BracketRight'
|
||
if (mod) {
|
||
e.preventDefault()
|
||
moveLayer(e.shiftKey ? (up ? 'top' : 'bottom') : (up ? 'up' : 'down'))
|
||
return
|
||
}
|
||
if (e.altKey) {
|
||
e.preventDefault()
|
||
selectNeighborLayer(up)
|
||
return
|
||
}
|
||
}
|
||
if (mod && key === 'z') {
|
||
e.preventDefault()
|
||
if (e.shiftKey) redo(); else undo()
|
||
return
|
||
}
|
||
// PS: Ctrl+Y 也等于重做(Windows 习惯)
|
||
if (mod && key === 'y') {
|
||
e.preventDefault()
|
||
redo()
|
||
return
|
||
}
|
||
}
|
||
|
||
function onKeyup(e) {
|
||
if (e.key === 'Shift') S._shiftDown = false
|
||
// PS:松开 Alt 结束临时吸管,回到画笔 / 橡皮
|
||
if (e.key === 'Alt') endAltPicker()
|
||
if (e.code === 'Space' && S.spaceDown) {
|
||
S.spaceDown = false
|
||
updateCursor()
|
||
}
|
||
}
|
||
|
||
// ============ 剪贴板粘贴(⌘/Ctrl+V 贴为新图层)============
|
||
/**
|
||
* 优先级:剪贴板里的图片文件(截图 / 复制图片)> text/html 里的 <img src>(网页里复制图片的形态)
|
||
* > text/plain 的图片 URL。命中即 preventDefault,进入「图片放置」模式 ——
|
||
* 与「导入图片为新图层」完全同一流程:拖动 / 缩放调好后点外部或回车确认,Esc 取消。
|
||
* 两个坑(都实测过):
|
||
* 1) URL 不能直接 new Image(url):跨域图会污染所有画布,导出时 toBlob 抛 SecurityError
|
||
* (表现是「图片跨域无法导出」)⇒ 必须 fetch→blob→dataURL(CSP connect-src 放行 https:);
|
||
* 反过来 data: URL 不能 fetch(connect-src 没有 data:,会被 CSP 拦),要直接走 loadImage。
|
||
* 2) 正在输入文字(isTyping)时不抢 text/html 与 text/plain 的粘贴 —— 用户可能就是想往文字输入框里贴 URL。
|
||
*/
|
||
function onPaste(e) {
|
||
if (!S.open) return
|
||
const cd = e.clipboardData
|
||
if (!cd) return
|
||
// ① 图片文件(截图 / 右键复制图片)
|
||
const items = cd.items || []
|
||
for (const item of items) {
|
||
if (item.kind === 'file' && /^image\//.test(item.type)) {
|
||
const file = item.getAsFile()
|
||
if (!file) continue
|
||
// 宿主在 window 气泡阶段也监听 paste(会把图片建成 ref 节点 + 触发下载)——
|
||
// 编辑器打开时这次粘贴归编辑器,必须掐断后续传播,否则一次粘贴出两层表现
|
||
e.preventDefault()
|
||
e.stopImmediatePropagation()
|
||
const reader = new FileReader()
|
||
reader.onload = async () => {
|
||
try { addBitmapLayer(await loadImage(reader.result)) }
|
||
catch (err) { console.error('[IWB编辑器] 粘贴图层失败:', err) }
|
||
}
|
||
reader.readAsDataURL(file)
|
||
return
|
||
}
|
||
}
|
||
if (isTyping(e)) return
|
||
// ② 网页复制的图片:text/html 里带 <img src="...">
|
||
const html = typeof cd.getData === 'function' ? (cd.getData('text/html') || '') : ''
|
||
if (html) {
|
||
const m = /<img[^>]*\ssrc\s*=\s*["']([^"']+)["']/i.exec(html)
|
||
if (m) { e.preventDefault(); e.stopImmediatePropagation(); pasteImageFromUrl(m[1]); return }
|
||
}
|
||
// ③ 纯文本:图片链接 / data URL
|
||
const text = (typeof cd.getData === 'function' ? (cd.getData('text/plain') || '') : '').trim()
|
||
if (/^(https?:\/\/\S+|data:image\/\S+)$/i.test(text)) { e.preventDefault(); e.stopImmediatePropagation(); pasteImageFromUrl(text); return }
|
||
}
|
||
|
||
/** 把 URL / data URL 的图片取回并贴为新图层;失败时给出可见提示(console + alert,编辑器没有 toast) */
|
||
async function pasteImageFromUrl(url) {
|
||
try {
|
||
let dataUrl = url
|
||
if (!/^data:image\//i.test(url)) {
|
||
const resp = await fetch(url)
|
||
if (!resp.ok) throw new Error('HTTP ' + resp.status)
|
||
const blob = await resp.blob()
|
||
if (!/^image\//.test(blob.type)) throw new Error('链接不是图片(' + (blob.type || '未知类型') + ')')
|
||
dataUrl = await new Promise((resolve, reject) => {
|
||
const reader = new FileReader()
|
||
reader.onload = () => resolve(reader.result)
|
||
reader.onerror = () => reject(new Error('图片读取失败'))
|
||
reader.readAsDataURL(blob)
|
||
})
|
||
}
|
||
addBitmapLayer(await loadImage(dataUrl))
|
||
} catch (err) {
|
||
console.error('[IWB编辑器] 粘贴图片链接失败:', err)
|
||
try { window.alert('粘贴失败:' + ((err && err.message) || '无法读取剪贴板里的图片链接')) } catch (e) { /* 忽略 */ }
|
||
}
|
||
}
|