/* snap.js - 拖动吸附与参考线(v1.9) * * 只做两件事:算「要不要吸、吸多少」,以及把参考线画出来。 * 不碰对象的写入 —— 调用方拿到 dx/dy 自己应用到 x/y,再在 render 里画线。 * 这样位图、文字、形状三种拖动可以共用同一套吸附,不会各写一遍阈值。 * * 吸附目标:画布中线/四边 + 其它可见元素的左/中/右与上/中/下。 * 阈值按屏幕像素给(6px),换算成图片像素后再比较 —— 否则放大图片时 * 吸附范围会跟着放大到几十像素,鼠标还没靠近就被拽走。 */ 'use strict' import { S } from './state.js' import { viewScale } from './scale.js' /** 吸附触发距离(屏幕像素) */ export const SNAP_SCREEN_PX = 6 /** 参考线颜色:洋红,和选中框的橙色区分开 */ const GUIDE_COLOR = '#ff2d95' function pushBox(targets, box) { const x2 = box.x + box.w const y2 = box.y + box.h targets.x.push(box.x, box.x + box.w / 2, x2) targets.y.push(box.y, box.y + box.h / 2, y2) } /** 在候选线里找「离得最近且不超过阈值」的那条,返回需要平移的量 */ function nearest(targets, sources, tol, axis) { let best = null for (let i = 0; i < targets.length; i++) { for (let j = 0; j < sources.length; j++) { const delta = targets[i] - sources[j] const abs = Math.abs(delta) if (abs > tol) continue if (!best || abs < Math.abs(best.delta)) best = { delta: delta, at: targets[i], axis: axis } } } return best } /** * 计算吸附位移。 * @param {{x:number,y:number,w:number,h:number}} box 被拖元素的包围盒(已按指针位移算好,未吸附) * @param {Array<{x:number,y:number,w:number,h:number}>} others 其它元素的包围盒 * @returns {{dx:number, dy:number, guides:Array}} */ export function snapMove(box, others) { const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale()) const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] } for (const o of others || []) { if (!o || !isFinite(o.x) || !isFinite(o.y)) continue pushBox(targets, o) } const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w] const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h] const gx = nearest(targets.x, sourcesX, tol, 'x') const gy = nearest(targets.y, sourcesY, tol, 'y') const guides = [] if (gx) guides.push(gx) if (gy) guides.push(gy) return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides: guides } } /** 画参考线(贯穿整个画布 + overlay 外扩区,拖动时一眼看到对齐到哪) */ export function drawGuides(ctx, guides) { if (!guides || !guides.length || !ctx) return const scale = viewScale() const pad = S.overlayPad || 0 ctx.save() ctx.strokeStyle = GUIDE_COLOR ctx.lineWidth = 1 / Math.max(0.02, scale) ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)]) for (const g of guides) { ctx.beginPath() if (g.axis === 'x') { ctx.moveTo(g.at, -pad) ctx.lineTo(g.at, S.imgH + pad) } else { ctx.moveTo(-pad, g.at) ctx.lineTo(S.imgW + pad, g.at) } ctx.stroke() } ctx.setLineDash([]) ctx.restore() } export function clearGuides() { if (!S.guides) return S.guides = null }