Files
iwb-plugins-desktop/image-annotate/plugin/editor/objects.js
T
qiqi 244fc9c2b2 feat(image-annotate): v1.14.0 文字可以选字体(黑 / 宋 / 楷 / 圆,系统字体族)
用户问「文字工具能不能选字体、难度大不大、性能要求高不高」。结论:能,核心只差
fontOf() 里硬编码的 'sans-serif',难度和性能都不是障碍 —— 真正的约束在字体文件怎么来。

实现(只做系统字体族,不做内置字体文件):
- text.js 新增 TEXT_FONTS(sans 黑体 / serif 宋体 / kai 楷体 / round 圆体),每个是一串
  跨平台候选栈:macOS 命中苹方/宋体,Windows 命中雅黑/宋体,全不命中退通用 sans-serif/serif。
- fontOf() 改为 weight + size + fontStackOf(t);fontKeyOf() 把 undefined / 脏值收敛回 sans,
  防止非法字符串进 ctx.font 让整串失效、静默退回浏览器默认(画面上看不出报错,极难排查)。
- 状态加 S.textFamily,对象加 fontFamily 字段;写回复用 TEXT_STYLE_STATE_KEY 一条路径,
  快照 cloneVectors 深拷贝天然带上,撤销/导出无需额外适配。
- 选项栏加「字体」下拉:唯一走 change 而非 click 的文字样式控件。
- 输入框同步字体族与字重,不会「输入时黑体、确认后宋体」。

为什么不做内置字体(三条硬约束):
1. 宿主 CSP 是 default-src 'self',font-src 回落它,第三方字体 CDN 会被直接拒绝;
2. CJK 字体本机宋体 2.3MB / 楷体 2.2MB / 苹方全字重 64MB,插件产物只有 392KB;
3. Web 字体异步,没 ready 就 measureText 会量出 fallback 宽度,选中框与字形错位、导出画错。

实测(1000²,30 个文字对象各一张整图画布):首次 13.2–42.1ms,热重绘 0.1–0.2ms ——
换字体只在首次多一次字形光栅化,之后走缓存,比现状还略快。中文全角等宽,换字体不改字宽
(10 字 48px 在 6 种字体下都是 480px),所以版面不跳动。另记既有开销:每对象一张整图画布,
1000² 3.8MB / 4000² 61MB,20 个对象在 4000² 上约 1.2GB(与字体无关)。

回归:harness 192 → 197(新增 5 条,含脏值收敛、中文宽度不变、撤销);validate 9/9;
真站 e2e 补 2 条字体断言。
2026-11-09 09:57:09 +08:00

764 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* objects.js - 文字、形状、钢笔与选择手柄
* 节:文字图层、形状图层、钢笔二次编辑、文字输入框。
* 矢量对象统一走 S.textLayers / S.shapeLayers 与 S.zCounter 排序,
* 渲染到 S.textCanvas(layers.js 负责它在图层栈里的位置)。
*/
'use strict'
import { S, runtime } from './state.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay, drawCropPreview } from './crop.js'
import { drawBitmapSelection, drawVectorToCanvas, hitBitmapAt, removeVecCanvas, renderLayerPanel, reorderLayerCanvas } from './layers.js'
import { drawPlacementPreview } from './placement.js'
import { drawShape, setTool } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { toast } from './commands.js'
import { renderOptionBar } from './events.js'
import { fontOf, fontStackOf, newTextStyle, textBox, weightOf } from './text.js'
import { drawGuides } from './snap.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============
/** 兼容旧调用点:TEXT_FONT(size) 返回粗体字体串;带样式的字体请用 text.js 的 fontOf(obj) */
export const TEXT_FONT = (size) => fontOf({ fontSize: size, fontWeight: 'bold' })
/** 文字包围盒:含多行、底色 padding 与描边外扩(单行时与旧实现完全一致) */
export function textBounds(t) {
return textBox(t)
}
export function getSelectedText() {
return S.textLayers.find(t => t.id === S.selectedTextId) || null
}
export function hitTextLayer(pos) {
for (let i = S.textLayers.length - 1; i >= 0; i--) {
const t = S.textLayers[i]
if (t.visible === false) continue
const b = textBounds(t)
const rot = t.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
if (lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 &&
lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2) {
return t
}
}
return null
}
function textHandlePoints(t) {
const b = textBounds(t)
const rot = t.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }
const out = {}
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot)
return out
}
export function hitTextHandle(pos) {
const t = getSelectedText()
if (!t) return null
const b = textBounds(t)
const rot = t.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in local) {
const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1]
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
// ============ 形状图层 ============
export function shapeBounds(s) {
if (s.type === 'pen' && s.pts && s.pts.length) { const xs = s.pts.map(p => p.x), ys = s.pts.map(p => p.y), x = Math.min(...xs), y = Math.min(...ys); return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y } }
return { x: Math.min(s.x1, s.x2), y: Math.min(s.y1, s.y2), w: Math.abs(s.x2 - s.x1), h: Math.abs(s.y2 - s.y1) }
}
export function getSelectedShape() {
return S.shapeLayers.find(s => s.id === S.selectedShapeId) || null
}
function distToSeg(px, py, x1, y1, x2, y2) {
const dx = x2 - x1, dy = y2 - y1
const l2 = dx * dx + dy * dy
let t = l2 ? ((px - x1) * dx + (py - y1) * dy) / l2 : 0
t = clamp(t, 0, 1)
return Math.hypot(px - (x1 + t * dx), py - (y1 + t * dy))
}
function hitShapeObj(pos, s, includeInterior) {
if (s.visible === false) return false
if (s.rotation) {
const b = shapeBounds(s)
const lp = unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, s.rotation)
pos = { x: lp[0], y: lp[1] }
}
if (s.type === 'pen') { const pts = s.pts || []; for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i-1].x, pts[i-1].y, pts[i].x, pts[i].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length-1].x, pts[pts.length-1].y, pts[0].x, pts[0].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (!includeInterior) return false; const b = shapeBounds(s); return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h }
if (s.type === 'circle') {
const b = shapeBounds(s)
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const rx = Math.max(0.5, b.w / 2), ry = Math.max(0.5, b.h / 2)
const nx = (pos.x - cx) / rx, ny = (pos.y - cy) / ry
const value = nx * nx + ny * ny
if (includeInterior || s.fill) return value <= 1
const edgeTolerance = Math.max(4 / viewScale(), s.lw / Math.min(rx, ry))
const outer = (1 + edgeTolerance) * (1 + edgeTolerance)
const inner = Math.max(0, 1 - edgeTolerance) * Math.max(0, 1 - edgeTolerance)
return value >= inner && value <= outer
}
if (s.type === 'rect') {
const b = shapeBounds(s)
const pad = Math.max(4, s.lw * 1.5)
const inOuter = pos.x >= b.x - pad && pos.x <= b.x + b.w + pad &&
pos.y >= b.y - pad && pos.y <= b.y + b.h + pad
if (!inOuter) return false
if (includeInterior || s.fill) return true
const inInner = pos.x >= b.x + pad && pos.x <= b.x + b.w - pad &&
pos.y >= b.y + pad && pos.y <= b.y + b.h - pad
return !inInner
}
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / viewScale(), s.lw)
}
export function hitShapeLayer(pos, includeInterior) {
for (let i = S.shapeLayers.length - 1; i >= 0; i--) {
if (hitShapeObj(pos, S.shapeLayers[i], includeInterior)) return S.shapeLayers[i]
}
return null
}
/** 所有对象(文字 + 形状)按 z 升序排列 */
export function allObjects() {
const arr = S.textLayers.map(o => ({ kind: 'text', obj: o }))
.concat(S.shapeLayers.map(o => ({ kind: 'shape', obj: o })))
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
return arr
}
export function sortLayersByZ() {
const cmp = (a, b) => (a.z || 0) - (b.z || 0)
S.textLayers.sort(cmp)
S.shapeLayers.sort(cmp)
}
/** 图层顺序的唯一真源:位图 + 矢量对象,按 z 升序。
* 之前位图(S.layers)与矢量(allObjects)各自排序、z 由两套计数器分配,
* 导致粘贴图片与图形 z 撞车、面板与画布叠放顺序相反、排序按钮交换 z 无效。 */
export function layerUnits() {
const arr = S.layers.map(obj => ({ kind: 'bitmap', obj }))
.concat(S.textLayers.map(obj => ({ kind: 'text', obj })))
.concat(S.shapeLayers.map(obj => ({ kind: 'shape', obj })))
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
return arr
}
/** 同一份列表按 z 降序(最上层在前):命中测试 / 图层面板共用 */
export function layerUnitsDesc() { return layerUnits().reverse() }
/** 重排后按索引重新分配连续 z,并同步 zCounter —— 杜绝重复 z */
export function assignLayerZ(units) {
units.forEach((u, i) => { u.obj.z = i })
S.zCounter = Math.max(S.zCounter, units.length - 1)
}
/** 选中态唯一入口:四个 id 一起写,杜绝「两个图层同时高亮 / 排序作用错对象」 */
export function selectUnit(kind, id) {
// 单选变了就退出「合并多选」:两套选择同时留着会让面板出现说不清的多个高亮
S.layerMulti.length = 0
S.selectedLayerId = kind === 'bitmap' ? id : null
S.selectedTextId = kind === 'text' ? id : null
S.selectedShapeId = kind === 'shape' ? id : null
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
// 选中态变了,选项栏要跟着换成该对象的参数(选择工具下改描边/实心/线宽/字号)
renderOptionBar()
}
/** 判定一个图层单元是否命中该点(位图用矩形/像素,矢量用包围盒/形状) */
export function hitUnit(unit, pos) {
const { kind, obj } = unit
if (!obj || obj.visible === false) return false
if (kind === 'bitmap') return obj.locked ? false : hitBitmapAt(obj, pos)
if (kind === 'text') {
const b = textBounds(obj)
const rot = obj.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
return lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 &&
lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2
}
return hitShapeObj(pos, obj, true)
}
/** 命中测试唯一入口:位图与矢量放同一份 z 降序列表里比较,最上层优先 */
export function hitTopmost(pos) {
for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit
return null
}
/** 其它可见元素的包围盒(拖动吸附用):排除自己与原图底图(底图边界=画布边界,重复) */
export function otherObjectBoxes(exclude) {
const out = []
for (const unit of layerUnits()) {
const o = unit.obj
if (!o || o === exclude || o.id === 'base' || o.visible === false) continue
if (unit.kind === 'bitmap') {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h })
} else if (unit.kind === 'text') {
out.push(textBox(o))
} else {
out.push(shapeBounds(o))
}
}
return out
}
export function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) {
if (unit.kind === 'bitmap') continue
if (hitUnit(unit, pos)) return unit
}
return null
}
function getSelectedObject() {
const t = getSelectedText()
if (t) return { kind: 'text', obj: t }
const s = getSelectedShape()
if (s) return { kind: 'shape', obj: s }
return null
}
/** 图层顺序调整(置顶 / 上移 / 下移 / 置底)
* 旧实现靠「交换相邻两项的 z」:一旦两个图层 z 相同(粘贴图片用 S.layers.length、
* 矢量用 ++S.zCounter,必然撞车),交换后仍是同一个值 ⇒ 按钮看起来没反应;
* 置底还会算出 -1 被不透明原图盖住。现在改成统一列表重排 + 重新分配连续 z。 */
export function moveLayer(dir) {
let sel = getSelectedObject()
if (sel) { if (sel.obj.locked) return } else {
const layer = S.layers.find(l => l.id === S.selectedLayerId && l.id !== 'base' && !l.locked)
if (layer) sel = { kind: 'bitmap', obj: layer }
}
// 快捷键(Ctrl+]/[)与按钮共用此入口:没选中时给出可见反馈,不再无声失败
if (!sel) { toast('先在画布或图层面板选中要调整的元素', 'info'); return }
if (sel.obj.locked || sel.obj.id === 'base') return
const units = layerUnits()
// v1.13:不再把原图钉在最底层 —— 「置底」可以真的沉到原图下面(垫背景层的常见用法)。
// 原图行本身仍不可参与(上面已 return),避免把底图整层挪走。
const from = units.findIndex(u => u.obj === sel.obj)
if (from < 0) return
const min = 0
let to
if (dir === 'up') to = Math.min(from + 1, units.length - 1)
else if (dir === 'down') to = Math.max(from - 1, min)
else if (dir === 'top') to = units.length - 1
else if (dir === 'bottom') to = min
else return
if (to === from) return
saveSnapshot()
const [moved] = units.splice(from, 1)
units.splice(to, 0, moved)
assignLayerZ(units)
sortLayersByZ()
reorderLayerCanvas()
renderObjects()
renderLayerPanel()
}
/** PS: Alt+] / Alt+[ 向上/向下选择图层(位图与矢量同一份 z 列表)。
* 当前没有任何选中时:向上选最顶层、向下选最底层,让用户能用键盘从头开始遍历。 */
export function selectNeighborLayer(up) {
const units = layerUnits()
if (!units.length) return
const sel = getSelectedObject()
let cur = -1
if (sel) cur = units.findIndex(u => u.obj === sel.obj)
else if (S.selectedLayerId) cur = units.findIndex(u => u.kind === 'bitmap' && u.obj.id === S.selectedLayerId)
const idx = cur < 0
? (up ? units.length - 1 : 0)
: (up ? Math.min(cur + 1, units.length - 1) : Math.max(cur - 1, 0))
const u = units[idx]
if (!u) return
selectUnit(u.kind, u.obj.id)
renderLayerPanel()
}
function shapeHandlePoints(s) {
const b = shapeBounds(s)
if (s.type === 'pen') {
return Object.fromEntries((s.pts || []).map((p, i) => ['p' + i, [p.x, p.y]]))
}
if (s.type === 'arrow') {
return { start: [s.x1, s.y1], end: [s.x2, s.y2] }
}
return {
nw: [b.x, b.y], ne: [b.x + b.w, b.y],
sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h],
n: [b.x + b.w / 2, b.y], s: [b.x + b.w / 2, b.y + b.h],
e: [b.x + b.w, b.y + b.h / 2], w: [b.x, b.y + b.h / 2]
}
}
/** 形状控制点的世界坐标(应用旋转后) */
function shapeHandleWorld(s) {
const b = shapeBounds(s)
const rot = s.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const local = shapeHandlePoints(s)
const out = {}
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot)
return out
}
export function hitShapeHandle(pos) {
const s = getSelectedShape()
if (!s) return null
const b = shapeBounds(s)
const rot = s.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const lp = rot ? unrotPt(pos.x, pos.y, cx, cy, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const pts = shapeHandlePoints(s)
const offset = 8 / viewScale()
const R = 14 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const px = pts[name][0] + (name.includes('w') ? -offset : name.includes('e') ? offset : 0)
const py = pts[name][1] + (name.includes('n') ? -offset : name.includes('s') ? offset : 0)
const dx = lp[0] - px, dy = lp[1] - py
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
export function applyShapeHandle(s, handle, pos) {
const b0 = shapeBounds(s)
const rot0 = s.rotation || 0
const c0x = b0.x + b0.w / 2, c0y = b0.y + b0.h / 2
if (handle === 'rotate') {
const st = S.shapeDrag && S.shapeDrag.start
const baseRot = (S.shapeDrag && S.shapeDrag.shape && (S.shapeDrag.shape.rotation || 0)) || 0
if (st) {
const a0 = Math.atan2(st.y - c0y, st.x - c0x)
const a1 = Math.atan2(pos.y - c0y, pos.x - c0x)
let deg = baseRot + (a1 - a0) * 180 / Math.PI
if (S._shiftDown) deg = Math.round(deg / 15) * 15
s.rotation = deg
}
return
}
const lp = rot0 ? unrotPt(pos.x, pos.y, c0x, c0y, rot0) : [pos.x, pos.y]
pos = { x: lp[0], y: lp[1] }
if (s.type === 'pen' && handle && handle[0] === 'p') {
const i = parseInt(handle.slice(1), 10)
if (s.pts && s.pts[i]) { s.pts[i].x = clamp(pos.x, 0, S.imgW); s.pts[i].y = clamp(pos.y, 0, S.imgH) }
return
}
if (s.type === 'arrow') {
if (handle === 'start') { s.x1 = clamp(pos.x, 0, S.imgW); s.y1 = clamp(pos.y, 0, S.imgH) }
else { s.x2 = clamp(pos.x, 0, S.imgW); s.y2 = clamp(pos.y, 0, S.imgH) }
return
}
const b = shapeBounds(s)
const offset = 8 / viewScale()
const adjusted = { x: pos.x - (handle.includes('w') ? -offset : handle.includes('e') ? offset : 0), y: pos.y - (handle.includes('n') ? -offset : handle.includes('s') ? offset : 0) }
let x1 = b.x, y1 = b.y, x2 = b.x + b.w, y2 = b.y + b.h
if (handle.includes('e')) x2 = Math.max(x1 + 2, adjusted.x)
if (handle.includes('s')) y2 = Math.max(y1 + 2, adjusted.y)
if (handle.includes('w')) x1 = Math.min(x2 - 2, adjusted.x)
if (handle.includes('n')) y1 = Math.min(y2 - 2, adjusted.y)
s.x1 = x1; s.y1 = y1; s.x2 = x2; s.y2 = y2
}
function drawPenPathPreview() {
const path = S.penPath
if (!path || !path.pts || !path.pts.length) return
const ctx = S.overlayCtx
const pts = path.pts.slice()
const first = pts[0]
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)
if (path.preview) pts.push(nearStart ? first : path.preview)
ctx.save()
ctx.strokeStyle = S.color
ctx.fillStyle = nearStart ? 'rgba(232, 167, 53, 0.18)' : 'transparent'
// 预览线宽 = 实际线宽(图片单位),不再除缩放,做到所见即所得
ctx.lineWidth = Math.max(1, S.shapeLineWidth)
ctx.setLineDash([8 / viewScale(), 5 / viewScale()])
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 (nearStart) { ctx.closePath(); ctx.fill() }
ctx.stroke()
ctx.setLineDash([])
for (let i = 0; i < path.pts.length; i++) {
const point = path.pts[i]
ctx.beginPath()
ctx.fillStyle = i === 0 && nearStart ? '#e8a735' : '#ffffff'
ctx.strokeStyle = S.color
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2)
ctx.fill(); ctx.stroke()
}
ctx.restore()
}
function drawShapeSelection(s) {
const octx = S.overlayCtx
const b = shapeBounds(s)
const rot = s.rotation || 0
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / viewScale()
// v1.10:对象选中框用**实线**。虚线在 PS 语义里是「像素选区(蚂蚁线)」,
// 用户看到文字/图形外面一圈虚线会当成「莫名其妙多出来的选区」。
const corners = boxCorners(b.x, b.y, b.w, b.h, rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1])
octx.closePath()
octx.stroke()
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = shapeHandleWorld(s)
for (const name in pts) {
octx.beginPath()
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
octx.fill()
octx.stroke()
}
octx.restore()
drawRotationHandles(octx, b, rot)
}
export function deleteSelectedShape() {
if (!S.selectedShapeId) return
const selected = getSelectedShape()
if (selected && selected.locked) return
saveSnapshot()
removeVecCanvas(selected)
S.shapeLayers = S.shapeLayers.filter(s => s.id !== S.selectedShapeId)
S.selectedShapeId = null
renderObjects()
}
/** 重绘对象层 + 选中态 */
export function renderObjects(tempShape) {
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj)
reorderLayerCanvas()
clearOverlay()
// 吸附参考线:拖动中才有值,松手清空。画在 overlay 层,不参与合成与导出
drawGuides(S.overlayCtx, S.guides)
if (tempShape) drawShape(S.overlayCtx, tempShape)
if (S.tool === 'pen' && S.penPath && S.penPath.pts.length) drawPenPathPreview()
// 图片放置模式优先显示放置预览
if (S.placingImage) {
drawPlacementPreview()
return
}
const bitmapSelection = S.layers.find(l => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l)))
if (bitmapSelection) drawBitmapSelection(bitmapSelection)
const sel = getSelectedText()
if (sel) {
const b = textBounds(sel)
const rot = sel.rotation || 0
const octx = S.overlayCtx
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / viewScale()
// 同上:对象选中是实线(虚线只留给像素选区的蚂蚁线)
const corners = boxCorners(b.x - 2 / viewScale(), b.y - 2 / viewScale(), b.w + 4 / viewScale(), b.h + 4 / viewScale(), rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1])
octx.closePath()
octx.stroke()
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = textHandlePoints(sel)
for (const name in pts) {
octx.beginPath()
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
octx.fill()
octx.stroke()
}
octx.restore()
} else {
const sh = getSelectedShape()
if (sh) drawShapeSelection(sh)
}
const penShape = getPenEditingShape()
if (penShape) drawPenEditOverlay(penShape)
if (S.cropRect) drawCropPreview()
}
// ============ 钢笔二次编辑(移动/添加/删除节点) ============
export function getPenEditingShape() {
if (!S.penEditId) return null
return S.shapeLayers.find(sh => sh.id === S.penEditId && sh.type === 'pen') || null
}
export function beginPenEdit(shape) {
S.penEditId = shape.id
S.selectedShapeId = shape.id
S.selectedTextId = null
S.selectedLayerId = null
S.shapeDrag = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
renderObjects()
renderLayerPanel()
}
export function exitPenEdit() {
S.penEditId = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
renderObjects()
renderLayerPanel()
}
export function hitPenPoint(pos, shape, r) {
const pts = shape.pts || []
const b = shapeBounds(shape)
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]
for (let i = 0; i < pts.length; i++) {
if (Math.hypot(lp[0] - pts[i].x, lp[1] - pts[i].y) <= r) return i
}
return -1
}
export function hitPenEdgeInsert(pos, shape) {
const pts = shape.pts || []
const b = shapeBounds(shape)
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]
const r = 12 / viewScale()
for (let i = 0; i < pts.length - 1; i++) {
if (distToSeg(lp[0], lp[1], pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= r) return i
}
if (shape.closed && pts.length >= 3) {
if (distToSeg(lp[0], lp[1], pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= r) return pts.length - 1
}
return -1
}
function drawPenEditOverlay(shape) {
const ctx = S.overlayCtx
const pts = shape.pts || []
const b = shapeBounds(shape)
const rot = shape.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const W = (p) => rotPt(p.x, p.y, cx, cy, rot)
const R = 7 / viewScale()
ctx.save()
ctx.lineWidth = 1.5 / viewScale()
const segments = []
for (let i = 0; i < pts.length - 1; i++) segments.push([pts[i], pts[i + 1]])
if (shape.closed && pts.length >= 3) segments.push([pts[pts.length - 1], pts[0]])
ctx.strokeStyle = '#e8a735'
for (const [a, bb] of segments) {
const wa = W(a), wb = W(bb)
const mx = (wa[0] + wb[0]) / 2, my = (wa[1] + wb[1]) / 2
ctx.beginPath()
ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2)
ctx.stroke()
}
for (let i = 0; i < pts.length; i++) {
const wp = W(pts[i])
ctx.beginPath()
ctx.rect(wp[0] - R / 2, wp[1] - R / 2, R, R)
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = i === S.penDragPt ? '#ff8c00' : '#e8a735'
ctx.fill()
ctx.stroke()
}
ctx.restore()
}
// ============ 文字输入框 ============
export function showTextInput(x, y, layer) {
const input = runtime.el.querySelector('.iwb-editor-text-input')
const wrapRect = S.canvasWrap.getBoundingClientRect()
// 不能用 canvasStack 的矩形换算:stack 的尺寸是 (imgW + 2*overlayPad) * scale,
// 图片在 stack 内部还额外偏移了 pad*scale(图层 canvas 的 left/top)。
// 拿它算比例会偏小、又漏掉这段偏移,输入框就整体跑到点击点的左上方。
// textCanvas 与图层 canvas 同基准,矩形精确等于「图片显示区域」。
const box = (S.textCanvas || S.canvasStack).getBoundingClientRect()
const sx = S.imgW ? box.width / S.imgW : 1
const sy = S.imgH ? box.height / S.imgH : 1
// textarea 有 2px 边框 + 8/4px 内边距,反向抵消后「输入框里的字起点」正压在点击点上,
// 与提交后 drawTextObject 从 t.x/t.y 起画的位置完全一致(所见即所得)。
const INSET_X = 10
const INSET_Y = 6
input.style.left = (box.left - wrapRect.left + x * sx - INSET_X) + 'px'
input.style.top = (box.top - wrapRect.top + y * sy - INSET_Y) + 'px'
input.style.display = 'block'
if (layer) {
input.value = layer.text
S.textEditingId = layer.id
} else {
input.value = ''
S.textEditingId = null
}
// 输入时看到的字形要和提交后一致:字体族与字重跟随这段文字自己的样式
// (新建时跟随「下一段文字的默认值」)。字号仍按 CSS 的 14px —— 那是输入框的可读性取舍,
// 跟字体不同:字体不一致会让人以为「选错字体了」,字号不一致只是大小不同。
const styleSrc = layer || { fontFamily: S.textFamily, fontWeight: S.textWeight }
input.style.fontFamily = fontStackOf(styleSrc)
input.style.fontWeight = weightOf(styleSrc)
input.focus()
input.select()
input.dataset.x = x
input.dataset.y = y
// textarea 不会自己长高:先按内容撑开,否则多行文本会挤在一行里
input.style.height = 'auto'
input.style.height = Math.max(30, input.scrollHeight + 4) + 'px'
}
export function hideTextInput() {
const input = runtime.el.querySelector('.iwb-editor-text-input')
if (input) {
// 必须先 blur:只隐藏不清焦点的话,焦点还留在隐藏的 input 上,
// 之后按 Esc 会被 isTyping() 当成"正在输入文字"吞掉(清不掉选中态)
if (document.activeElement === input) input.blur()
input.style.display = 'none'
input.value = ''
}
S.textEditingId = null
}
export function commitTextInput() {
const input = runtime.el.querySelector('.iwb-editor-text-input')
if (!input || input.style.display === 'none') return false
const text = input.value.trim()
const x = parseFloat(input.dataset.x)
const y = parseFloat(input.dataset.y)
let committed = false
if (S.textEditingId) {
const t = S.textLayers.find(l => l.id === S.textEditingId)
if (t && t.locked) { hideTextInput(); return true }
if (t && text !== t.text) {
saveSnapshot()
if (text) {
t.text = text
} else {
removeVecCanvas(t)
S.textLayers = S.textLayers.filter(l => l.id !== t.id)
S.selectedTextId = null
}
renderObjects()
}
committed = true
} else if (text) {
saveSnapshot()
const layer = {
id: 't' + Date.now() + Math.floor(Math.random() * 1000),
x, y, text,
color: S.color,
fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight, fontFamily: S.textFamily, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}),
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
}
S.textLayers.push(layer)
selectUnit('text', layer.id)
renderObjects()
committed = true
}
hideTextInput()
// 文字落成即回 V 并选中(用户 2026-11-05):输入完下一步通常是挪位置 / 改字号颜色。
// 必须延后一个微任务 —— setTool 第一行就是 commitTextInput(),同步调用会自我递归。
// 延后期间若又开了新输入框(在 T 下连续点着输入),就不要把工具抢走。
if (committed) {
const id = S.selectedTextId
queueMicrotask(() => {
if (S.tool !== 'text') return
const box = runtime.el && runtime.el.querySelector('.iwb-editor-text-input')
if (box && box.style.display !== 'none') return
setTool('select')
if (!id) return
selectUnit('text', id)
renderObjects()
renderLayerPanel()
})
}
return committed
}
export function deleteSelectedText() {
if (!S.selectedTextId) return
const selected = getSelectedText()
if (selected && selected.locked) return
saveSnapshot()
removeVecCanvas(selected)
S.textLayers = S.textLayers.filter(t => t.id !== S.selectedTextId)
S.selectedTextId = null
renderObjects()
}
export function beginTextRotate(pos) {
const t = getSelectedText()
if (!t || t.locked) return
const b = textBounds(t)
S.textDrag = {
mode: 'rotate',
rotation: t.rotation || 0,
cx: b.x + b.w / 2,
cy: b.y + b.h / 2,
startX0: pos.x,
startY0: pos.y,
pending: snapshotState()
}
}
export function beginTextScaleDrag(handle, pos) {
const t = getSelectedText()
if (!t || t.locked) return
const b = textBounds(t)
const rot = t.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const anchors = {
se: [b.x, b.y],
ne: [b.x, b.y + b.h],
sw: [b.x + b.w, b.y],
nw: [b.x + b.w, b.y + b.h]
}
const a = rotPt(anchors[handle][0], anchors[handle][1], cx, cy, rot)
const anchor = { x: a[0], y: a[1] }
const dx = pos.x - anchor.x, dy = pos.y - anchor.y
S.textDrag = {
mode: 'scale',
anchor,
d0: Math.sqrt(dx * dx + dy * dy),
fontSize: t.fontSize,
pending: snapshotState()
}
}
export function beginShapeHandleDrag(handle, pos) {
const sh = getSelectedShape()
if (!sh || sh.locked) return
S.shapeDrag = {
mode: 'handle', handle,
start: pos,
shape: { ...sh },
pending: snapshotState()
}
}