Files
iwb-plugins-desktop/image-annotate/plugin/editor/objects.js
T
qiqi b63771f6e4 feat(image-annotate): v1.10.0 颜色语义统一、选中框改实线、选区命令归位、矢量图形补描边与填充
四个问题来自同一张界面截图,都是真缺陷。

1) 三处颜色各司其职。'#ff4444'/'#ffffff'/'#000000'/0.68 这些默认值原先散在
state.js、text.js、events.js 三处,改一处另两处不跟 —— 界面上就成了「同一个
概念三种颜色」。现在 text.js 导出 TEXT_DEFAULTS 做单点定义,state.js 与选项栏
都从这里取。三个色块统一外观但标记「生效状态」:描边宽度 0 / 底色关闭 /
图形处于描边模式时,色块显示灰色斜纹(不显示颜色本身),语义是「这里还没有
颜色」;只做半透明灰化不够,深色照样是一块黑方块。文字底色默认从纯黑 #000000
改为中性近黑 #101014(68% 透明),色块按真实不透明度渲染。选描边色时若宽度
为 0 自动给 6px,与「选底色即开底色」同一条原则。

2) 选中框从虚线改实线。虚线在修图软件里的语义是像素选区(蚂蚁线),文字外面
套一圈虚线会被当成「多出来一个删不掉的选区」。objects.js 的文字/形状、
layers.js 的位图图层三处同步改为实线,虚线只留给真正的像素选区。

3) 选区命令(全选/反选/取消)归位到选区工具。它们操作的是像素选区,跟文字对象
无关:以前挂在「选中文字/图形」的选项栏里,选中文字就冒出来;而矩形/套索
选区工具反而没有。现在选区工具有,选择工具「未选中任何元素」时也有。

4) 矢量图形补上描边色与填充色。每个形状新增独立 fillColor;描边色不再另起一份,
直接复用主色(左侧色板/吸管/选项栏一个真相源,四处永远同步)。fillColor===null
表示跟随描边色,于是新画的实心图形是同色实心,换主色整块跟着变。
矩形/圆形/钢笔/箭头的选项栏都出「描边 ■ / 填充 ■」色块(箭头无填充区域,只给
描边色);选中对象读它自己的值,没选中时改的是新建默认值。选填充色即自动切
实心,色块从斜纹变成实际颜色。「样式 描边/实心」也改成读选中对象自己的 fill
(以前只看全局默认值,选中已实心的矩形却高亮「描边」,和画面反着来)。

顺带简化:文本样式与形状颜色共用同一套色块控件与 CSS,is-off 用斜纹 +
虚线边框;底色色块用 --sw-a 变量体现半透明。

harness 162 → 172 条全通(新增:默认色不写死、色块生效态、选区命令归位、
选中框实线覆盖率 ≥0.85、图形描边/填充色与实际像素);validate 9/9。
harness 自身两处改法:清选中改用「切到别的工具再切回」(画布上早有别的用例
留下的图形,点空白会点到它们);像素断言改成全画布统计同色像素
(矢量画布含 overlayPad 外扩,按图片坐标换算单点会采到别处)。
2026-11-08 21:24:38 +08:00

760 lines
29 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, updateLayerUI } from './events.js'
import { fontOf, newTextStyle, textBox } 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()
// base 是锁定且不透明的底图,固定在最下层;任何元素都不许置底到它下面(否则等于消失)
const baseIdx = units.findIndex(u => u.obj.id === 'base')
if (baseIdx > 0) { const [b] = units.splice(baseIdx, 1); units.unshift(b) }
const from = units.findIndex(u => u.obj === sel.obj)
if (from < 0) return
const min = baseIdx >= 0 ? 1 : 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()
updateLayerUI()
}
// ============ 钢笔二次编辑(移动/添加/删除节点) ============
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
}
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, 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()
}
}