fix(image-annotate): v1.8.2 选择框控制点尺寸固定为屏幕像素

现象:选中图形时,控制点巨大(约 100px 的发光方块),大小随图片尺寸变化、与缩放无关。

根因:控制点、旋转手柄、虚线间距、命中半径全部写成 5.5 / S.zoom。
但 S.zoom 是「相对 fitW 的倍数」,不是「图片像素→屏幕像素」的比例。叠加 overlay
画布按 viewScale 拉伸后,真实屏幕尺寸 = 11 * fitW / imgW —— 只跟图片尺寸走:
小图被适应窗口放大 5~10 倍时膨胀到 100px,大图缩到 4px 看不见。
zoomStep 的 anchor 换算是另一个语义(相对 fitW 单位),保持 / S.zoom 不动。

顺带发现第二个问题:overlay 画布的像素缓冲等于图片尺寸,小图放大后 UI 叠层糊成光斑。

修法:
- 新增 plugin/editor/scale.js(零依赖叶子模块)
  viewScale() = fitW*zoom/imgW;overlayScale() = clamp(fitW/imgW, 1, 4);
  resetOverlayTransform(cx) = 恢复「图片坐标 + pad + 倍率」
- 7 个文件共 30 余处 UI 常量改为 X / viewScale();去掉 Math.max(X/zoom, N)
  的托底(N 是图片单位,放大时会变成巨大命中区,导致误触)
- overlay / selection / cursor 三张画布按 overlayScale 建缓冲,绘制坐标仍是图片单位,
  所以全部绘制代码无需改动;四处置空函数(crop/selection/tools/index)改用设备像素
  clearRect + resetOverlayTransform 恢复

必须做成叶子模块:viewport 与 crop/objects/layers 存在循环 import,把换算放在循环里
esbuild 打成 IIFE 后另一侧拿到 undefined —— 实测 clearOverlay 报
"resetOverlayTransform is not defined",编辑器直接打不开(已踩过)。

实测(Playwright 按屏幕分辨率重采样后量像素包围盒):
  96x64    控制点 7~8px   旧实现 101.5px   overlay 288x256 -> 1152x1024
  800x600  控制点 8~9px   旧实现 12.2px
  2400x1800 控制点 9~10px 旧实现 4.1px
纯白内区比视觉尺寸小 1.5px(描边压边),视觉上稳定 11px。

验证:harness 140 项全通(新增 1 项控制点尺寸断言)、validate 9/9。
This commit is contained in:
qiqi committed 2026-11-08 17:49:16 +08:00
1 parent fccb9ae69e
commit 6e1685998f
14 files changed
+320 -154

No files matched your search

+13 -11
View File
@@ -7,6 +7,7 @@
import { S, runtime } from './state.js'
import { resizeWorkspace } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { disposeSelection } from './selection.js'
import { saveSnapshot } from './history.js'
import { toast } from './commands.js'
@@ -82,12 +83,13 @@ import { toast } from './commands.js'
export function clearOverlay() {
const ctx = S.overlayCtx
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
if (!ctx) return
// 缓冲已按 overlayScale 放大,必须按设备像素整幅清,再恢复图片坐标基准
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
export function drawCropPreview(x1, y1, x2, y2) {
@@ -112,8 +114,8 @@ import { toast } from './commands.js'
ctx.restore()
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.strokeRect(rx, ry, rw, rh)
ctx.restore()
if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh)
@@ -131,11 +133,11 @@ import { toast } from './commands.js'
function drawCropHandles(rx, ry, rw, rh) {
const ctx = S.overlayCtx
const pts = cropHandlePoints(rx, ry, rw, rh)
const hs = 4 / S.zoom
const hs = 4 / viewScale()
ctx.save()
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
ctx.lineWidth = 1.5 / viewScale()
for (const name in pts) {
ctx.beginPath()
ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
@@ -153,7 +155,7 @@ import { toast } from './commands.js'
export function hitCropHandle(pos) {
if (!S.cropRect) return null
const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h)
const R = 12 / S.zoom
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1]
+6 -5
View File
@@ -8,6 +8,7 @@
import { S, ZOOM_STEP, runtime } from './state.js'
import { ROT_CURSOR, clamp, getPos, isOverRotationHandle, setView, setZoomActual, setZoomFit, zoomStep } from './viewport.js'
import { viewScale } from './scale.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'
@@ -91,7 +92,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
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)
Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / viewScale(), 6)
S.lastClick = hit ? null : { t: now, x: pos.x, y: pos.y }
return hit
}
@@ -104,7 +105,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
function onCanvasDoubleClick(e, pos) {
const penShape = getPenEditingShape()
if (penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(14 / S.zoom, 8))
const pi = hitPenPoint(pos, penShape, Math.max(14 / viewScale(), 8))
if (pi < 0) return false
e.preventDefault()
saveSnapshot()
@@ -173,7 +174,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔节点编辑中的按下:点节点拖动/点边插点返回 true(已接管);点空白退出编辑返回 false 继续走工具逻辑 */
function onPenEditMouseDown(e, pos, penShape) {
const pi = hitPenPoint(pos, penShape, Math.max(16 / S.zoom, 9))
const pi = hitPenPoint(pos, penShape, Math.max(16 / viewScale(), 9))
if (pi >= 0) {
S.penDragPt = pi
S.penDragBase = JSON.parse(JSON.stringify(penShape.pts))
@@ -309,7 +310,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
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)) {
if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)) {
S.penPath.closed = true
S.penPath.nearStart = true
S.penPath.preview = null
@@ -493,7 +494,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
/** 钢笔路径预览:更新悬停点与起点闭合提示 */
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)
const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)
S.penPath.nearStart = !!nearStart
renderObjects() }
}
+3 -3
View File
@@ -32,6 +32,7 @@ import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.
import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput } from './objects.js'
import { setupCanvas } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
@@ -139,10 +140,9 @@ import { toast } from './commands.js'
hideSelectionContext()
if (S.selectionCtx) renderSelection()
if (S.cursorCtx) {
const pad = S.overlayPad || 0
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad)
S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height)
resetOverlayTransform(S.cursorCtx)
}
}
+5 -4
View File
@@ -10,6 +10,7 @@
import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { drawShape } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { placeImageDirectly } from './placement.js'
@@ -115,7 +116,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const rot = layer.rotation || 0
const cx = box.x + box.w / 2, cy = box.y + box.h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
const R = 14 / S.zoom
const R = 14 / viewScale()
if (hitRotationHandle(lp, box)) return 'rotate'
const points = {
nw: [box.x, box.y], ne: [box.x + box.w, box.y],
@@ -201,11 +202,11 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
if (!(box.w > 0 && box.h > 0)) return
const ctx = S.overlayCtx
const rot = layer.rotation || 0
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
ctx.save()
ctx.strokeStyle = '#e8a735'
ctx.lineWidth = 1.5 / S.zoom
ctx.setLineDash([6 / S.zoom, 3 / S.zoom])
ctx.lineWidth = 1.5 / viewScale()
ctx.setLineDash([6 / viewScale(), 3 / viewScale()])
const corners = boxCorners(box.x, box.y, box.w, box.h, rot)
ctx.beginPath()
ctx.moveTo(corners[0][0], corners[0][1])
+24 -22
View File
@@ -8,6 +8,7 @@
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'
@@ -67,7 +68,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom
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]
@@ -103,7 +104,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom, 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 / S.zoom, 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 === '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
@@ -111,7 +112,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom, s.lw / Math.min(rx, ry))
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
@@ -127,7 +128,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom, s.lw)
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) {
@@ -310,8 +311,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom
const R = Math.max(14 / S.zoom, 9)
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)
@@ -352,7 +353,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
return
}
const b = shapeBounds(s)
const offset = 8 / S.zoom
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)
@@ -368,13 +369,14 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 / S.zoom, S.shapeLineWidth * 1.5)
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) / S.zoom
ctx.setLineDash([8 / S.zoom, 5 / S.zoom])
// 预览线宽 = 实际线宽(图片单位),不再除缩放,做到所见即所得
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)
@@ -386,7 +388,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
ctx.beginPath()
ctx.fillStyle = i === 0 && nearStart ? '#e8a735' : '#ffffff'
ctx.strokeStyle = S.color
ctx.arc(point.x, point.y, Math.max(4, 6 / S.zoom), 0, Math.PI * 2)
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2)
ctx.fill(); ctx.stroke()
}
ctx.restore()
@@ -398,8 +400,8 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const rot = s.rotation || 0
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
octx.lineWidth = 1.5 / viewScale()
octx.setLineDash([6 / viewScale(), 3 / viewScale()])
const corners = boxCorners(b.x, b.y, b.w, b.h, rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
@@ -407,7 +409,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
octx.closePath()
octx.stroke()
octx.setLineDash([])
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = shapeHandleWorld(s)
@@ -453,16 +455,16 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
const octx = S.overlayCtx
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
const corners = boxCorners(b.x - 2 / S.zoom, b.y - 2 / S.zoom, b.w + 4 / S.zoom, b.h + 4 / S.zoom, rot)
octx.lineWidth = 1.5 / viewScale()
octx.setLineDash([6 / viewScale(), 3 / 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()
octx.setLineDash([])
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = textHandlePoints(sel)
@@ -522,7 +524,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 = Math.max(12 / S.zoom, 6)
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
}
@@ -539,9 +541,9 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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 = Math.max(7 / S.zoom, 5)
const R = 7 / viewScale()
ctx.save()
ctx.lineWidth = 1.5 / S.zoom
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]])
@@ -550,7 +552,7 @@ import { isDrawableLayer } from '../vendor/layer-logic.js'
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, Math.max(3 / S.zoom, 2), 0, Math.PI * 2)
ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2)
ctx.stroke()
}
for (let i = 0; i < pts.length; i++) {
+10 -9
View File
@@ -8,6 +8,7 @@
import { S } from './state.js'
import { boxCorners, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
import { saveSnapshot } from './history.js'
@@ -131,8 +132,8 @@ import { updateCursor } from './events.js'
const corners = boxCorners(x, y, w, h, rot)
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.beginPath()
ctx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1])
@@ -140,10 +141,10 @@ import { updateCursor } from './events.js'
ctx.stroke()
ctx.setLineDash([])
// 8 个缩放手柄(旋转后位置)
const hs = 5.5 / S.zoom
const hs = 5.5 / viewScale()
ctx.fillStyle = '#fff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
ctx.lineWidth = 1.5 / viewScale()
const localPts = {
nw: [x, y], ne: [x + w, y],
sw: [x, y + h], se: [x + w, y + h],
@@ -162,17 +163,17 @@ import { updateCursor } from './events.js'
drawRotationHandles(ctx, { x, y, w, h }, rot)
// 提示文字
ctx.save()
ctx.font = 'bold ' + Math.round(14 / S.zoom) + 'px sans-serif'
ctx.font = 'bold ' + Math.round(14 / viewScale()) + 'px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'top'
const hintText = '拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消'
const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity)
const hintY = br + 10 / S.zoom
const hintY = br + 10 / viewScale()
const tw = ctx.measureText(hintText).width
ctx.fillStyle = 'rgba(0,0,0,0.6)'
ctx.fillRect(cx - tw / 2 - 6 / S.zoom, hintY, tw + 12 / S.zoom, 22 / S.zoom)
ctx.fillRect(cx - tw / 2 - 6 / viewScale(), hintY, tw + 12 / viewScale(), 22 / viewScale())
ctx.fillStyle = 'rgba(255,255,255,0.95)'
ctx.fillText(hintText, cx, hintY + 4 / S.zoom)
ctx.fillText(hintText, cx, hintY + 4 / viewScale())
ctx.restore()
}
@@ -182,7 +183,7 @@ import { updateCursor } from './events.js'
const rot = S.placingImage.rotation || 0
const cx = x + w / 2, cy = y + h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
const R = 12 / S.zoom
const R = 12 / viewScale()
// 四角外侧圆弧 = 旋转手柄
if (hitRotationHandle(lp, { x, y, w, h })) return 'rotate'
const pts = {
+49
View File
@@ -0,0 +1,49 @@
/* scale.js - 视图缩放换算(零依赖叶子模块,只读 S)
*
* 为什么单独成文件:这三个函数被 viewport / objects / layers / crop / selection /
* placement / events 共用,而 viewport 与 crop、objects、layers 之间存在**循环 import**。
* 把换算函数放在有循环的模块里,esbuild 打成 IIFE 后另一侧会拿到 undefined:
* 实测 clearOverlay 报 "resetOverlayTransform is not defined"(setupCanvas 调 clearOverlay,
* 此时 viewport 模块尚在求值中)。叶子模块没有反向依赖,任何时候都可用。
*/
'use strict'
import { S } from './state.js'
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
export function viewScale() {
return (S.imgW && S.fitW) ? (S.fitW * S.zoom) / S.imgW : 1
}
/**
* overlay 系列画布(选中框 / 蚂蚁线 / 笔刷环)的像素倍率。
*
* 这三张画布的像素缓冲原本就等于「图片尺寸 + padding」,CSS 再按 viewScale 拉伸显示。
* 小图被「适应窗口」放大 5~10 倍时缓冲严重不足,控制点、虚线全糊成一团发光点。
*
* 倍率只看适应窗口的基准比例(fitW / imgW,**不含 zoom**):拖动缩放不会改变它,
* 所以不会在缩放过程中反复重建 canvas。上限 4 是为内存 —— 缓冲面积按平方增长。
*/
export function overlayScale() {
const base = (S.imgW && S.fitW) ? S.fitW / S.imgW : 1
return Math.max(1, Math.min(4, base))
}
/** 把 ctx 重置到「图片坐标」基准:含 pad 偏移与 overlayScale 倍率。
* 清屏后必须用它恢复,否则后续绘制会按 1:1 铺到设备像素上、整体偏移。 */
export function resetOverlayTransform(cx) {
const k = overlayScale()
const pad = S.overlayPad || 0
cx.setTransform(k, 0, 0, k, pad * k, pad * k)
}
+6 -7
View File
@@ -13,6 +13,7 @@
import { S } from './state.js'
import { clamp, getPos } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { defineCommand, runCommand, toast } from './commands.js'
import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
@@ -32,23 +33,21 @@ import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCan
function clearSelectionCanvas() {
const ctx = S.selectionCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
export function clearCursorCanvas() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
/** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */
@@ -56,7 +55,7 @@ import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCan
if (!S.selectionCtx) return
clearSelectionCanvas()
const ctx = S.selectionCtx
const k = 1 / Math.max(S.zoom, 0.0001)
const k = 1 / Math.max(viewScale(), 0.0001)
// 拉框 / 套索过程中:画预览,不画正式选区
if (S.marquee || (S.lassoPts && S.lassoPts.length > 1)) {
+3 -3
View File
@@ -12,6 +12,7 @@ import { commitTextInput, getSelectedShape, getSelectedText, layerUnits, renderO
import { cancelCrop, clearOverlay, hideCropBar, showCropBar, updateCropInfo } from './crop.js'
import { cancelImagePlacement } from './placement.js'
import { clamp } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { getActiveCtx, getActiveLayer, renderLayerPanel } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js'
@@ -222,12 +223,11 @@ import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
export function clearToolRing() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
resetOverlayTransform(ctx)
}
/** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */
+32 -13
View File
@@ -7,6 +7,7 @@
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.js'
import { overlayScale, resetOverlayTransform, viewScale } from './scale.js'
import { bindCanvasEvents, updateZoomUI } from './events.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, purgeVectorCanvases, renderLayerPanel, styleVectorViewport } from './layers.js'
@@ -46,11 +47,14 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.strokeCanvas.style.display = 'none'
// 裁剪越界区域属于交互工作区,不改变图片本身的画布尺寸。
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
// overlayScale 依赖 fitW,必须先算出适应尺寸再建交互层缓冲
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
// 创建图层 1: 原图
@@ -82,7 +86,6 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
renderObjects()
computeFit()
S.viewX = null
applyView()
renderLayerPanel()
@@ -108,11 +111,13 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
purgeVectorCanvases()
@@ -124,7 +129,6 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
S.pickerComposite = null
clearOverlay()
computeFit()
S.viewX = null
applyView()
renderObjects()
@@ -238,6 +242,18 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
export function clamp(v, min, max) { return Math.max(min, Math.min(max, v)) }
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
// ============ 旋转辅助 ============
export function rotPt(px, py, cx, cy, deg) {
if (!deg) return [px, py]
@@ -251,7 +267,8 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
/** 旋转手柄:四个角沿对角线向外偏移(局部坐标) */
function rotationHandlesLocal(b) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const d = 26 / Math.max(S.zoom, 0.0001)
// 26 屏幕像素的间距,换算成图片单位(不能除以 S.zoom,否则随图片尺寸漂移)
const d = 26 / Math.max(viewScale(), 0.0001)
return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map(c => {
const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1
return [c[0] + dx / len * d, c[1] + dy / len * d]
@@ -260,7 +277,9 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
/** 命中旋转手柄(传局部坐标点) */
export function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b)
const R = Math.max(11 / Math.max(S.zoom, 0.0001), 8)
// 11 屏幕像素的命中半径。原先用 Math.max(..., 8) 托底,但托底值是图片单位,
// 放大显示时会变成巨大的屏幕命中区(误触),故只按 viewScale 换算。
const R = 11 / Math.max(viewScale(), 0.0001)
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true
}
@@ -270,10 +289,10 @@ import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBoun
export function drawRotationHandles(ctx, b, rot) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const pts = rotationHandlesLocal(b)
const k = Math.max(S.zoom, 0.0001)
const r = Math.max(6.5 / k, 5)
const k = Math.max(viewScale(), 0.0001)
const r = 6.5 / k
const lw = 1.5 / k
const ah = Math.max(3 / k, 2.6) // 箭头长度
const ah = 3 / k // 箭头长度
const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72
ctx.save()
ctx.strokeStyle = '#f0b34e'