Files
iwb-plugins-desktop/image-annotate/plugin/editor/viewport.js
T

331 lines
13 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.
/* viewport.js - 画布尺寸、缩放平移、旋转辅助与坐标换算
* 节:画布设置、旋转辅助、坐标。
* 约定:所有屏幕坐标 <-> 图片坐标的换算都过 getPos/rotPt/unrotPt,
* 缩放状态只写 S.zoom / S.viewX / S.viewY。
*/
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.js'
import { bindCanvasEvents, updateZoomUI } from './events.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, purgeVectorCanvases, renderLayerPanel, styleVectorViewport } from './layers.js'
import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBounds } from './objects.js'
// ============ 画布设置 ============
/** 三张交互层(选中框/蚂蚁线/笔刷环)共享同一尺寸与坐标基准,但各自清屏互不影响 */
function syncOverlayCanvas() {
const pad = S.overlayPad || 0
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
const w = Math.round((S.imgW + pad * 2) * scale) + 'px'
const h = Math.round((S.imgH + pad * 2) * scale) + 'px'
for (const c of [S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
if (!c) continue
c.style.left = '0px'
c.style.top = '0px'
c.style.width = w
c.style.height = h
}
}
export function setupCanvas(img) {
purgeVectorCanvases()
// 清除旧的动态图层 canvas
for (const layer of S.layers) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
}
S.layers = []
// 设置工具 canvas 尺寸
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.strokeCanvas.style.display = 'none'
// 裁剪越界区域属于交互工作区,不改变图片本身的画布尺寸。
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
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)
}
// 创建图层 1: 原图
const baseCanvas = createLayerCanvas()
const baseCtx = baseCanvas.getContext('2d', { willReadFrequently: true })
baseCtx.clearRect(0, 0, S.imgW, S.imgH)
baseCtx.drawImage(img, 0, 0)
S.layers.push({
id: 'base',
name: '原图',
canvas: baseCanvas,
ctx: baseCtx,
opacity: 1,
visible: true,
locked: true,
z: 0
})
// 默认不再预建「画笔标注」空层(用户裁定 2026-11-04:需要时自己加)。
// 画笔起笔时 ensureWritableLayer() 会自动落一个「标注 N」层兜底,
// 所以这里活动层指向原图(锁定态),不会误画到原图上。
S.activeLayerId = 'base'
S.zCounter = 1
S.textCtx.clearRect(0, 0, S.imgW, S.imgH)
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH)
clearOverlay()
S.pickerComposite = null
renderObjects()
computeFit()
S.viewX = null
applyView()
renderLayerPanel()
bindCanvasEvents()
}
/**
* 只调整画布尺寸与交互层,不重建图层(裁剪 / 撤销裁剪共用)。
*
* 与 setupCanvas 的分工:setupCanvas 会清空 S.layers 并新建「原图 + 画笔」两层,
* 那是「打开一张新图」的语义。裁剪只是在同一张图上换视窗,像素由调用方先搬好,
* 这里只负责尺寸、交互层、矢量层与视图基准,图层结构原样保留。
*
* ⚠️ 这里会把每个图层 canvas 的像素缓冲清空(canvas.width 赋值即重置),
* 调用方必须在调用前把像素复制出来,调用后写回。
*/
export function resizeWorkspace(w, h) {
S.imgW = Math.max(1, Math.round(w))
S.imgH = Math.max(1, Math.round(h))
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
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))
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)
}
purgeVectorCanvases()
for (const layer of S.layers) {
layer.canvas.width = S.imgW
layer.canvas.height = S.imgH
layer._bounds = undefined
}
S.pickerComposite = null
clearOverlay()
computeFit()
S.viewX = null
applyView()
renderObjects()
renderLayerPanel()
}
/** 计算「适应容器」的基准显示尺寸(不限制放大,小图也铺满) */
function computeFit() {
// 底部浮动工具栏(Figma 风格)压在画布下沿,给它预留出高度,
// 否则适应窗口后图片下边缘会被工具栏盖住。
const TOOLBAR_RESERVE = 72
const availW = Math.max(50, S.canvasWrap.clientWidth - 48)
const availH = Math.max(50, S.canvasWrap.clientHeight - 48 - TOOLBAR_RESERVE)
const ratio = Math.min(availW / S.imgW, availH / S.imgH)
S.fitW = Math.max(1, S.imgW * ratio)
S.fitH = Math.max(1, S.imgH * ratio)
}
/**
* 应用当前 zoom 与平移位置到画布显示尺寸与位置(自由平移,无边界限制)。
* @param {object} anchor 可选 { mx, my, px, py }:缩放锚点
*/
function applyView(anchor) {
const w = Math.round(S.fitW * S.zoom)
const h = Math.round(S.fitH * S.zoom)
// 更新所有 canvas 的显示尺寸(位图图层 + 工具层)
for (const layer of S.layers) {
layer.canvas.style.width = w + 'px'
layer.canvas.style.height = h + 'px'
}
S.textCanvas.style.width = S.strokeCanvas.style.width = w + 'px'
S.textCanvas.style.height = S.strokeCanvas.style.height = h + 'px'
syncOverlayCanvas()
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
if (S.transparencyGrid) {
S.transparencyGrid.style.left = Math.round((S.overlayPad || 0) * scale) + 'px'
S.transparencyGrid.style.top = Math.round((S.overlayPad || 0) * scale) + 'px'
S.transparencyGrid.style.width = w + 'px'
S.transparencyGrid.style.height = h + 'px'
}
// 显式固定 stack 尺寸,保证统一坐标基准始终可测量,新增/隐藏图层不会触发布局偏移。
const pad = S.overlayPad || 0
S.canvasStack.style.width = Math.round((S.imgW + pad * 2) * scale) + 'px'
S.canvasStack.style.height = Math.round((S.imgH + pad * 2) * scale) + 'px'
const layerOffset = Math.round(pad * scale)
for (const layer of S.layers) {
layer.canvas.style.left = layerOffset + 'px'
layer.canvas.style.top = layerOffset + 'px'
}
S.textCanvas.style.left = layerOffset + 'px'
S.textCanvas.style.top = layerOffset + 'px'
S.strokeCanvas.style.left = layerOffset + 'px'
S.strokeCanvas.style.top = layerOffset + 'px'
styleVectorViewport(w, h, layerOffset)
let left, top
if (anchor && anchor.mx !== undefined) {
left = anchor.mx - anchor.px * S.zoom
top = anchor.my - anchor.py * S.zoom
} else if (S.viewX !== null) {
left = S.viewX
top = S.viewY
} else {
left = (S.canvasWrap.clientWidth - w) / 2
top = (S.canvasWrap.clientHeight - h) / 2
}
setView(left, top)
updateZoomUI()
}
/** 设置画布平移位置(自由坐标,无边界限制) */
export function setView(x, y) {
S.viewX = x
S.viewY = y
const stack = S.canvasStack
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
const pad = S.overlayPad || 0
// 让原图左上角仍对应 viewX/viewY,外围 padding 不参与画布平移坐标。
stack.style.transform = `translate3d(${Math.round(x - pad * scale)}px, ${Math.round(y - pad * scale)}px, 0)`
}
/** 以指定屏幕坐标(wrap 内)为中心缩放 */
export function zoomStep(factor, mx, my) {
const nz = clamp(S.zoom * factor, ZOOM_MIN, ZOOM_MAX)
if (nz === S.zoom) return
const px = (mx - (S.viewX || 0)) / S.zoom
const py = (my - (S.viewY || 0)) / S.zoom
S.zoom = nz
applyView({ mx, my, px, py })
}
/**
* 适应窗口:先按当前容器尺寸重算基准显示尺寸,再回到 zoom=1 并居中。
* 只写 zoom=1 不够 —— 窗口/侧栏变过之后 fitW/fitH 还是旧值,点了看起来「没反应」。
*/
export function setZoomFit() {
computeFit()
S.zoom = 1
S.viewX = null
applyView()
}
/** 100% 实际像素(PS: Ctrl+1)。S.zoom 是相对 fitW 的倍数,所以要换算。 */
export function setZoomActual() {
computeFit()
S.zoom = clamp(S.fitW ? S.imgW / S.fitW : 1, ZOOM_MIN, ZOOM_MAX)
S.viewX = null
applyView()
}
export function clamp(v, min, max) { return Math.max(min, Math.min(max, v)) }
// ============ 旋转辅助 ============
export function rotPt(px, py, cx, cy, deg) {
if (!deg) return [px, py]
const a = deg * Math.PI / 180, sn = Math.sin(a), cs = Math.cos(a)
const dx = px - cx, dy = py - cy
return [cx + dx * cs - dy * sn, cy + dx * sn + dy * cs]
}
export function unrotPt(px, py, cx, cy, deg) {
return rotPt(px, py, cx, cy, -(deg || 0))
}
/** 旋转手柄:四个角沿对角线向外偏移(局部坐标) */
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)
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]
})
}
/** 命中旋转手柄(传局部坐标点) */
export function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b)
const R = Math.max(13 / Math.max(S.zoom, 0.0001), 9)
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true
}
return false
}
/** 绘制四个角外侧的圆弧旋转手柄 */
export function drawRotationHandles(ctx, b, rot) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const pts = rotationHandlesLocal(b)
const r = Math.max(8 / Math.max(S.zoom, 0.0001), 6)
ctx.save()
ctx.strokeStyle = '#e8a735'
ctx.lineWidth = 2 / Math.max(S.zoom, 0.0001)
for (const pt of pts) {
const w = rotPt(pt[0], pt[1], cx, cy, rot || 0)
ctx.beginPath()
ctx.arc(w[0], w[1], r, Math.PI * 0.15, Math.PI * 1.85)
ctx.stroke()
}
ctx.restore()
}
export const ROT_CURSOR = 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'24\' height=\'24\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'black\' stroke-width=\'2\' stroke-linecap=\'round\'><path d=\'M21 12a9 9 0 1 1-3-6.7\'/><polyline points=\'21 3 21 9 15 9\'/></svg>") 12 12, crosshair'
/** 指针是否悬停在当前选中对象(或放置中图片)的旋转手柄上 */
export function isOverRotationHandle(p) {
if (S.placingImage) {
const b = { x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h }
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, S.placingImage.rotation || 0)
return hitRotationHandle(lp, b)
}
const t = getSelectedText()
if (t) {
const b = textBounds(t)
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, t.rotation || 0)
return hitRotationHandle(lp, b)
}
const sh = getSelectedShape()
if (sh) {
const b = shapeBounds(sh)
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, sh.rotation || 0)
return hitRotationHandle(lp, b)
}
const layer = S.layers.find(l => l.id === S.selectedLayerId && l.transformable)
if (layer) {
const lp = unrotPt(p.x, p.y, layer.x + layer.w / 2, layer.y + layer.h / 2, layer.rotation || 0)
return hitRotationHandle(lp, layer)
}
return false
}
export function boxCorners(x, y, w, h, rot) {
const cx = x + w / 2, cy = y + h / 2
return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(pt => rotPt(pt[0], pt[1], cx, cy, rot))
}
// ============ 坐标 ============
export function getPos(e) {
// 统一使用 stack 的边界作为坐标基准。图层 canvas 可能被隐藏,或在
// 插入/重排时暂时不参与布局;以具体图层 boundingRect 计算会造成左移。
const rect = S.canvasStack.getBoundingClientRect()
const pad = S.overlayPad || 0
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
return {
x: (e.clientX - rect.left) / Math.max(scale, 0.0001) - pad,
y: (e.clientY - rect.top) / Math.max(scale, 0.0001) - pad
}
}