- detectTextStyle(hit):OCR框顶边斜率→角度、行高×0.82→字号、框内墨迹
中位色→颜色(白/黑/灰/彩色命名)、中心行带横向行程中位数→粗体判定;
背景中位色取框外环带,距离阈值60分离墨迹
- hitPreviewLayer(text):输入新字→按检测样式构造临时文字层原位重绘,
过原框宽1.15倍自动缩号;render() 在消除预览之上绘制(输入即所见)
- applyHitReplace 重写:inpainting 背景扩散重建擦原字(弃色块覆盖)→
同样式重绘新字居中原框 → 一步历史「无痕改字」;检测失败退回旧色块路径
- 选项栏:「检出 白色·粗·109px·5.2°」检测徽标 + placeholder 提示原文字;
statusHint 加 selHit 分支;「🧹 消除文字」改「只消除」
- hitStyle 在 Escape/init/applyPreview 各清理点同步置空
- 实测:渐变背景白色粗体"人数8"倾斜-10° → 检出 白色·109px·5.2° →
输入"31"实时预览 → 回车 图层=文字「31」+智能消除+背景、历史一步 →
导出像素验证:原区域白字仅剩新"31"(2688px)、背景平滑视觉无痕
2781 lines
86 KiB
Vue
2781 lines
86 KiB
Vue
<script setup lang="ts">
|
||
// PS 风格图片编辑器:工具栏 / 选项栏 / 画布(缩放平移)/ 图层面板 / 历史记录
|
||
// 图层类型:image(底图) / paint(画笔涂改层) / text(文字层) / fill(色块擦除层)
|
||
import { useStorage } from '@vueuse/core';
|
||
import { licenseHeaders } from '@/tools/license/license';
|
||
import { TEXT_TPLS, TPL_CATS, tplStyle, filterTpls, type TextTpl } from './text-tpls';
|
||
|
||
const props = defineProps<{ file: File; autoTpl?: TextTpl | null }>();
|
||
const emit = defineEmits<{ (e: 'error', msg: string): void; (e: 'applied'): void }>();
|
||
let autoTplConsumed = false; // 上传前模板墙套用一次性标记
|
||
|
||
// ---------- 文档状态 ----------
|
||
const docW = ref(0);
|
||
const docH = ref(0);
|
||
let baseCanvas: HTMLCanvasElement | null = null; // 底图像素(不直接参与图层合成,作为 image 图层缓存)
|
||
let compCanvas: HTMLCanvasElement | null = null; // 合成缓存(doc 分辨率)
|
||
|
||
interface TextLayer {
|
||
id: string; type: 'text'; name: string; visible: boolean; opacity: number;
|
||
text: string; x: number; y: number; size: number; color: string; bold: boolean;
|
||
rot: number; // 旋转角(度,绕文字框中心)
|
||
// 花字样式(模板套用,均可空)
|
||
grad?: [string, string] | null; // 渐变填充
|
||
stroke?: string | null; // 描边色
|
||
strokeW?: number; // 描边宽(相对字号比例)
|
||
shadow?: string | null; // 投影色
|
||
badge?: string | null; // 色块底(红底白字类)
|
||
}
|
||
|
||
|
||
interface FillLayer {
|
||
id: string; type: 'fill'; name: string; visible: boolean; opacity: number;
|
||
x: number; y: number; w: number; h: number; color: string;
|
||
}
|
||
interface PaintLayer {
|
||
id: string; type: 'paint'; name: string; visible: boolean; opacity: number;
|
||
ox: number; oy: number; canvas: HTMLCanvasElement;
|
||
}
|
||
interface ImageLayer {
|
||
id: string; type: 'image'; name: string; visible: boolean; opacity: number;
|
||
}
|
||
type Layer = TextLayer | FillLayer | PaintLayer | ImageLayer;
|
||
|
||
const layers = ref<Layer[]>([]);
|
||
const activeLayerId = ref('');
|
||
const activeLayer = computed(() => layers.value.find(l => l.id === activeLayerId.value) ?? null);
|
||
|
||
// ---------- 工具 ----------
|
||
type Tool = 'move' | 'marquee' | 'brush' | 'eraser' | 'text' | 'fill' | 'eyedropper' | 'crop' | 'hand';
|
||
const TOOLS: { key: Tool; icon: string; title: string }[] = [
|
||
{ key: 'move', icon: '✥', title: '移动 (V):拖动文字/色块图层,或拖动当前画笔层' },
|
||
{ key: 'marquee', icon: '▦', title: '选框 (M):框选区域后可填充/清除' },
|
||
{ key: 'brush', icon: '🖌', title: '画笔 (B)' },
|
||
{ key: 'eraser', icon: '🩹', title: '智能消除笔 (E):直接涂文字/水印,松手即无痕消除;选中画笔层时擦除笔迹' },
|
||
{ key: 'text', icon: 'T', title: '文字 (T):点击画布放置文字层' },
|
||
{ key: 'fill', icon: '🪣', title: '油漆桶 (G):点击相近颜色区域填充' },
|
||
{ key: 'eyedropper', icon: '💧', title: '吸管 (I):取色' },
|
||
{ key: 'crop', icon: '✂', title: '裁剪 (C):框选后点「应用裁剪」' },
|
||
{ key: 'hand', icon: '✋', title: '抓手 (H):拖动平移,滚轮缩放' },
|
||
];
|
||
const tool = useStorage<Tool>('image-tools:psx-tool', 'move');
|
||
const brushSize = useStorage('image-tools:psx-brush', 16);
|
||
const brushColor = useStorage('image-tools:psx-color', '#d03050');
|
||
const tolerance = useStorage('image-tools:psx-tol', 28);
|
||
const newText = useStorage('image-tools:psx-text', '新文字');
|
||
const fontSize = useStorage('image-tools:psx-font-v2', 100); // 默认 100 号(v2 key 避免旧 36 缓存)
|
||
const tplCat = ref('全部'); // 模板分类标签
|
||
const sideTpls = computed(() => filterTpls(tplCat.value));
|
||
const fontColor = useStorage('image-tools:psx-fontcolor', '#ffffff');
|
||
const fontBold = useStorage('image-tools:psx-bold', true);
|
||
|
||
// ---------- 视图 ----------
|
||
const viewEl = ref<HTMLDivElement>();
|
||
const viewCanvas = ref<HTMLCanvasElement>();
|
||
const zoom = ref(1);
|
||
const panX = ref(0);
|
||
const panY = ref(0);
|
||
const hover = ref<{ x: number; y: number } | null>(null);
|
||
let resizeObs: ResizeObserver | null = null;
|
||
|
||
const statusHint = computed(() => {
|
||
if (selHit.value) {
|
||
return hitStyle.value
|
||
? `无痕改字:已检出原字「${hitStyle.value.colorName}${hitStyle.value.bold ? '·粗体' : ''}·${hitStyle.value.size}px${hitStyle.value.angle ? `·${hitStyle.value.angle}°` : ''}」→ 输入新文字实时预览,回车无缝替换`
|
||
: `原字「${selHit.value.text}」→ 输入新文字实时预览,回车无缝替换(或「🧹 只消除」)`;
|
||
}
|
||
if (tool.value === 'eraser') {
|
||
return activeLayer.value?.type === 'paint'
|
||
? `画笔层擦除:大小 ${brushSize.value}px,按 [ ] 调整`
|
||
: `智能消除笔:在文字/水印上涂抹,松手立即无痕消除(${brushSize.value}px,[ ] 调整)`;
|
||
}
|
||
if (tool.value === 'brush') {
|
||
return `大小 ${brushSize.value}px,按 [ ] 调整`;
|
||
}
|
||
if (tool.value === 'move') {
|
||
return '拖动文字/色块;选中画笔层后可整体移动';
|
||
}
|
||
if (tool.value === 'marquee') {
|
||
return '拖拽框选,松手后可「消除选区内容」(无痕去文字/水印)或填充/清除';
|
||
}
|
||
if (tool.value === 'text') {
|
||
return activeLayer.value?.type === 'text'
|
||
? '拖动文字移动;拖顶部蓝点旋转(Shift 吸附15°);拖四角方块直接缩放字号;右侧模板一键换花字'
|
||
: '右侧模板点击即插入整组文案(可连点多组);点中某行文字后再点模板=只换样式';
|
||
}
|
||
if (tool.value === 'move' && !activeLayer.value) {
|
||
return '点右侧✨文字模板插入整组标题文案;点中文字可拖动/旋转/拖四角方块缩放字号';
|
||
}
|
||
if (tool.value === 'fill') {
|
||
return '点击图片相近颜色区域填充(容差 ' + tolerance.value + ')';
|
||
}
|
||
if (tool.value === 'crop') {
|
||
return '拖拽框选裁剪区域后点「应用裁剪」';
|
||
}
|
||
if (tool.value === 'hand') {
|
||
return '拖动平移画布,滚轮缩放';
|
||
}
|
||
return '点击画布取色';
|
||
});
|
||
|
||
const cursorCss = computed(() => {
|
||
if (tool.value === 'hand') {
|
||
return 'grab';
|
||
}
|
||
if (tool.value === 'move' || tool.value === 'text' || tool.value === 'fill' || tool.value === 'eyedropper') {
|
||
return 'default';
|
||
}
|
||
return 'crosshair';
|
||
});
|
||
|
||
// ---------- 历史记录 ----------
|
||
interface HistEntry { label: string; state: string } // state = JSON(paint 层像素存 dataURL)
|
||
const hist = ref<HistEntry[]>([]);
|
||
const hIdx = ref(-1);
|
||
const HIST_MAX = 20;
|
||
|
||
function uid(): string {
|
||
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||
}
|
||
|
||
function serializeState(): string {
|
||
const ls = layers.value.map((l) => {
|
||
if (l.type === 'paint') {
|
||
return { id: l.id, type: l.type, name: l.name, visible: l.visible, opacity: l.opacity, ox: l.ox, oy: l.oy, data: l.canvas.toDataURL('image/png') };
|
||
}
|
||
return { ...l };
|
||
});
|
||
return JSON.stringify({ w: docW.value, h: docH.value, active: activeLayerId.value, layers: ls });
|
||
}
|
||
|
||
async function restoreState(s: string): Promise<void> {
|
||
preview.value = null;
|
||
const st = JSON.parse(s);
|
||
docW.value = st.w;
|
||
docH.value = st.h;
|
||
const ls: Layer[] = [];
|
||
for (const raw of st.layers) {
|
||
if (raw.type === 'paint') {
|
||
const c = document.createElement('canvas');
|
||
c.width = st.w;
|
||
c.height = st.h;
|
||
await new Promise<void>((resolve) => {
|
||
const im = new Image();
|
||
im.onload = () => {
|
||
c.getContext('2d')!.drawImage(im, 0, 0);
|
||
resolve();
|
||
};
|
||
im.onerror = () => resolve();
|
||
im.src = raw.data;
|
||
});
|
||
ls.push({ id: raw.id, type: 'paint', name: raw.name, visible: raw.visible, opacity: raw.opacity, ox: raw.ox ?? 0, oy: raw.oy ?? 0, canvas: c });
|
||
}
|
||
else {
|
||
const l = raw as Layer;
|
||
if (l.type === 'text' && l.rot === undefined) {
|
||
l.rot = 0; // 兼容旧历史数据
|
||
}
|
||
ls.push(l);
|
||
}
|
||
}
|
||
layers.value = ls;
|
||
activeLayerId.value = st.active ?? ls[ls.length - 1]?.id ?? '';
|
||
ensureComp();
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function commit(label: string): void {
|
||
preview.value = null; // 图层已变化,旧预览作废
|
||
hist.value = hist.value.slice(0, hIdx.value + 1);
|
||
hist.value.push({ label, state: serializeState() });
|
||
if (hist.value.length > HIST_MAX) {
|
||
hist.value.shift();
|
||
}
|
||
hIdx.value = hist.value.length - 1;
|
||
}
|
||
|
||
async function undo(): Promise<void> {
|
||
if (hIdx.value <= 0) {
|
||
return;
|
||
}
|
||
hIdx.value--;
|
||
await restoreState(hist.value[hIdx.value].state);
|
||
}
|
||
|
||
async function redo(): Promise<void> {
|
||
if (hIdx.value >= hist.value.length - 1) {
|
||
return;
|
||
}
|
||
hIdx.value++;
|
||
await restoreState(hist.value[hIdx.value].state);
|
||
}
|
||
|
||
async function jumpHist(i: number): Promise<void> {
|
||
if (i === hIdx.value) {
|
||
return;
|
||
}
|
||
hIdx.value = i;
|
||
await restoreState(hist.value[i].state);
|
||
}
|
||
|
||
// ---------- 合成与渲染 ----------
|
||
function ensureComp(): void {
|
||
if (!compCanvas) {
|
||
compCanvas = document.createElement('canvas');
|
||
}
|
||
compCanvas.width = docW.value;
|
||
compCanvas.height = docH.value;
|
||
}
|
||
|
||
function drawLayerTo(ctx: CanvasRenderingContext2D, l: Layer): void {
|
||
if (!l.visible) {
|
||
return;
|
||
}
|
||
ctx.globalAlpha = Math.max(0, Math.min(1, l.opacity / 100));
|
||
if (l.type === 'image') {
|
||
if (baseCanvas) {
|
||
ctx.drawImage(baseCanvas, 0, 0);
|
||
}
|
||
}
|
||
else if (l.type === 'paint') {
|
||
ctx.drawImage(l.canvas, l.ox, l.oy);
|
||
}
|
||
else if (l.type === 'fill') {
|
||
ctx.fillStyle = l.color;
|
||
ctx.fillRect(l.x, l.y, l.w, l.h);
|
||
}
|
||
else if (l.type === 'text') {
|
||
drawTextLayer(ctx, l);
|
||
}
|
||
ctx.globalAlpha = 1;
|
||
}
|
||
|
||
function composite(): void {
|
||
if (!compCanvas || !docW.value) {
|
||
return;
|
||
}
|
||
const ctx = compCanvas.getContext('2d')!;
|
||
ctx.clearRect(0, 0, docW.value, docH.value);
|
||
for (const l of layers.value) {
|
||
drawLayerTo(ctx, l);
|
||
}
|
||
}
|
||
|
||
let renderScheduled = false;
|
||
function scheduleRender(): void {
|
||
if (renderScheduled) {
|
||
return;
|
||
}
|
||
renderScheduled = true;
|
||
requestAnimationFrame(() => {
|
||
renderScheduled = false;
|
||
render();
|
||
});
|
||
}
|
||
|
||
const lastView = { w: 0, h: 0 };
|
||
let checkerPattern: CanvasPattern | null = null;
|
||
function getChecker(ctx: CanvasRenderingContext2D): CanvasPattern {
|
||
if (!checkerPattern) {
|
||
const c = document.createElement('canvas');
|
||
c.width = 16;
|
||
c.height = 16;
|
||
const cc = c.getContext('2d')!;
|
||
cc.fillStyle = '#cccccc';
|
||
cc.fillRect(0, 0, 16, 16);
|
||
cc.fillStyle = '#ffffff';
|
||
cc.fillRect(0, 0, 8, 8);
|
||
cc.fillRect(8, 8, 8, 8);
|
||
checkerPattern = ctx.createPattern(c, 'repeat')!;
|
||
}
|
||
return checkerPattern;
|
||
}
|
||
|
||
// 文字层几何:以文字框中心为旋转锚点
|
||
function textCenter(l: TextLayer): { x: number; y: number } {
|
||
const m = textMetrics(l);
|
||
return { x: l.x + m.w / 2, y: l.y + m.h / 2 };
|
||
}
|
||
|
||
// 旋转手柄位置(框顶部中心外推 26px 屏幕距离)
|
||
function textHandlePos(l: TextLayer): { x: number; y: number } {
|
||
const m = textMetrics(l);
|
||
const c = textCenter(l);
|
||
const dist = m.h / 2 + 26 / zoom.value;
|
||
const a = (l.rot * Math.PI) / 180;
|
||
return { x: c.x + Math.sin(a) * dist, y: c.y - Math.cos(a) * dist };
|
||
}
|
||
|
||
// 四角缩放手柄位置(选框四角,随文字旋转)
|
||
function textCornerPositions(l: TextLayer): { x: number; y: number }[] {
|
||
const m = textMetrics(l);
|
||
const c = textCenter(l);
|
||
const a = (l.rot * Math.PI) / 180;
|
||
const cos = Math.cos(a);
|
||
const sin = Math.sin(a);
|
||
const hw = m.w / 2 + 3 / zoom.value;
|
||
const hh = m.h / 2 + 3 / zoom.value;
|
||
return ([[ -hw, -hh ], [ hw, -hh ], [ -hw, hh ], [ hw, hh ]] as const).map(([lx, ly]) => ({
|
||
x: c.x + lx * cos - ly * sin,
|
||
y: c.y + lx * sin + ly * cos,
|
||
}));
|
||
}
|
||
|
||
// 旋转命中:把点逆旋转回文字局部空间再比对
|
||
function textHitTest(l: TextLayer, dx: number, dy: number): boolean {
|
||
const m = textMetrics(l);
|
||
const c = textCenter(l);
|
||
const a = (-l.rot * Math.PI) / 180;
|
||
const ox = dx - c.x;
|
||
const oy = dy - c.y;
|
||
const rx = ox * Math.cos(a) - oy * Math.sin(a);
|
||
const ry = ox * Math.sin(a) + oy * Math.cos(a);
|
||
return Math.abs(rx) <= m.w / 2 + 6 && Math.abs(ry) <= m.h / 2 + 6;
|
||
}
|
||
|
||
// 花字绘制:色块底 → 投影 → 描边 → 渐变/纯色填充(绕文字框中心旋转)
|
||
function drawTextLayer(ctx: CanvasRenderingContext2D, l: TextLayer): void {
|
||
const font = `${l.bold ? 'bold ' : ''}${l.size}px "Microsoft YaHei","PingFang SC","Noto Sans CJK SC","Source Han Sans SC",sans-serif`;
|
||
ctx.font = font;
|
||
ctx.textAlign = 'center';
|
||
ctx.textBaseline = 'middle';
|
||
const w = ctx.measureText(l.text).width;
|
||
const h = l.size * 1.25;
|
||
const cx = l.x + w / 2;
|
||
const cy = l.y + h / 2;
|
||
ctx.save();
|
||
ctx.translate(cx, cy);
|
||
if (l.rot) {
|
||
ctx.rotate((l.rot * Math.PI) / 180);
|
||
}
|
||
// 1) 色块底(红底白字类,四周留字距)
|
||
if (l.badge) {
|
||
const px = l.size * 0.32;
|
||
const py = l.size * 0.24;
|
||
const bx = -w / 2 - px;
|
||
const by = -h / 2 - py;
|
||
const bw = w + px * 2;
|
||
const bh = h + py * 2;
|
||
const r = Math.min(bh / 2, l.size * 0.18);
|
||
ctx.fillStyle = l.badge;
|
||
ctx.beginPath();
|
||
ctx.moveTo(bx + r, by);
|
||
ctx.lineTo(bx + bw - r, by);
|
||
ctx.arcTo(bx + bw, by, bx + bw, by + r, r);
|
||
ctx.lineTo(bx + bw, by + bh - r);
|
||
ctx.arcTo(bx + bw, by + bh, bx + bw - r, by + bh, r);
|
||
ctx.lineTo(bx + r, by + bh);
|
||
ctx.arcTo(bx, by + bh, bx, by + bh - r, r);
|
||
ctx.lineTo(bx, by + r);
|
||
ctx.arcTo(bx, by, bx + r, by, r);
|
||
ctx.closePath();
|
||
ctx.fill();
|
||
}
|
||
// 2) 投影
|
||
if (l.shadow) {
|
||
ctx.shadowColor = l.shadow;
|
||
ctx.shadowBlur = l.size * 0.22;
|
||
ctx.shadowOffsetX = l.size * 0.07;
|
||
ctx.shadowOffsetY = l.size * 0.1;
|
||
}
|
||
// 3) 描边(描边宽 = strokeW × 字号,居中描边故 ×2)
|
||
if (l.stroke) {
|
||
ctx.lineJoin = 'round';
|
||
ctx.miterLimit = 2;
|
||
ctx.lineWidth = (l.strokeW ?? 0.08) * l.size * 2;
|
||
ctx.strokeStyle = l.stroke;
|
||
ctx.strokeText(l.text, 0, 0);
|
||
// 去投影再填充,避免填充被投影糊掉
|
||
ctx.shadowColor = 'transparent';
|
||
ctx.shadowBlur = 0;
|
||
ctx.shadowOffsetX = 0;
|
||
ctx.shadowOffsetY = 0;
|
||
}
|
||
// 4) 填充(渐变或纯色)
|
||
if (l.grad) {
|
||
const g = ctx.createLinearGradient(-w / 2, 0, w / 2, 0);
|
||
g.addColorStop(0, l.grad[0]);
|
||
g.addColorStop(1, l.grad[1]);
|
||
ctx.fillStyle = g;
|
||
}
|
||
else {
|
||
ctx.fillStyle = l.color;
|
||
}
|
||
ctx.fillText(l.text, 0, 0);
|
||
ctx.restore();
|
||
ctx.shadowColor = 'transparent';
|
||
ctx.shadowBlur = 0;
|
||
ctx.shadowOffsetX = 0;
|
||
ctx.shadowOffsetY = 0;
|
||
ctx.textAlign = 'start';
|
||
ctx.textBaseline = 'alphabetic';
|
||
}
|
||
|
||
function textMetrics(l: TextLayer): { w: number; h: number } {
|
||
const c = viewCanvas.value ?? document.createElement('canvas');
|
||
const ctx = c.getContext('2d')!;
|
||
ctx.font = `${l.bold ? 'bold ' : ''}${l.size}px "Microsoft YaHei","PingFang SC","Noto Sans CJK SC",sans-serif`;
|
||
return { w: ctx.measureText(l.text).width, h: l.size * 1.25 };
|
||
}
|
||
|
||
function render(): void {
|
||
const c = viewCanvas.value;
|
||
const host = viewEl.value;
|
||
if (!c || !host || !docW.value) {
|
||
return;
|
||
}
|
||
const dpr = window.devicePixelRatio || 1;
|
||
const vw = host.clientWidth;
|
||
const vh = host.clientHeight;
|
||
if (c.width !== Math.round(vw * dpr) || c.height !== Math.round(vh * dpr)) {
|
||
// 视口尺寸变化:按中心补偿平移,保持图像居中(否则布局稳定后图片会偏移)
|
||
if (lastView.w) {
|
||
panX.value += (vw - lastView.w) / 2;
|
||
panY.value += (vh - lastView.h) / 2;
|
||
}
|
||
lastView.w = vw;
|
||
lastView.h = vh;
|
||
c.width = Math.round(vw * dpr);
|
||
c.height = Math.round(vh * dpr);
|
||
c.style.width = `${vw}px`;
|
||
c.style.height = `${vh}px`;
|
||
}
|
||
const ctx = c.getContext('2d')!;
|
||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||
ctx.clearRect(0, 0, vw, vh);
|
||
ctx.save();
|
||
ctx.translate(panX.value, panY.value);
|
||
ctx.scale(zoom.value, zoom.value);
|
||
// 文档区:棋盘格 + 合成图
|
||
ctx.fillStyle = getChecker(ctx);
|
||
ctx.fillRect(0, 0, docW.value, docH.value);
|
||
if (compCanvas) {
|
||
ctx.drawImage(compCanvas, 0, 0);
|
||
}
|
||
// 实时消除预览(未应用前直接盖在合成图上)
|
||
if (preview.value) {
|
||
ctx.drawImage(preview.value.canvas, preview.value.x, preview.value.y);
|
||
}
|
||
// 无痕改字实时预览:输入新字 → 按检测样式原位重绘(所见即所得)
|
||
if (selHit.value && hitText.value.trim()) {
|
||
const hpl = hitPreviewLayer(hitText.value.trim());
|
||
if (hpl) {
|
||
drawTextLayer(ctx, hpl);
|
||
}
|
||
}
|
||
ctx.strokeStyle = 'rgba(0,0,0,0.45)';
|
||
ctx.lineWidth = 1 / zoom.value;
|
||
ctx.strokeRect(0, 0, docW.value, docH.value);
|
||
// 选中图层边框
|
||
const al = activeLayer.value;
|
||
if (al && al.type !== 'image' && al.visible) {
|
||
ctx.strokeStyle = '#2563eb';
|
||
ctx.lineWidth = 1.5 / zoom.value;
|
||
ctx.setLineDash([5 / zoom.value, 3 / zoom.value]);
|
||
if (al.type === 'text') {
|
||
const m = textMetrics(al);
|
||
const c = textCenter(al);
|
||
ctx.save();
|
||
ctx.translate(c.x, c.y);
|
||
if (al.rot) {
|
||
ctx.rotate((al.rot * Math.PI) / 180);
|
||
}
|
||
ctx.strokeRect(-m.w / 2 - 3 / zoom.value, -m.h / 2 - 3 / zoom.value, m.w + 6 / zoom.value, m.h + 6 / zoom.value);
|
||
// 旋转手柄:框顶部中心外 26px(屏幕恒定距离)
|
||
ctx.setLineDash([]);
|
||
const hd = m.h / 2 + 26 / zoom.value;
|
||
ctx.beginPath();
|
||
ctx.moveTo(0, -m.h / 2 - 3 / zoom.value);
|
||
ctx.lineTo(0, -hd);
|
||
ctx.stroke();
|
||
ctx.beginPath();
|
||
ctx.arc(0, -hd, 5 / zoom.value, 0, Math.PI * 2);
|
||
ctx.fillStyle = '#2563eb';
|
||
ctx.fill();
|
||
ctx.strokeStyle = '#fff';
|
||
ctx.lineWidth = 1.5 / zoom.value;
|
||
ctx.stroke();
|
||
// 四角缩放手柄:白色小方块,拖动直接调字号
|
||
const hsz = 7 / zoom.value;
|
||
const hw2 = m.w / 2 + 3 / zoom.value;
|
||
const hh2 = m.h / 2 + 3 / zoom.value;
|
||
ctx.fillStyle = '#fff';
|
||
ctx.strokeStyle = '#2563eb';
|
||
for (const hc of [[-1, -1], [1, -1], [-1, 1], [1, 1]] as const) {
|
||
ctx.beginPath();
|
||
ctx.rect(hc[0] * hw2 - hsz / 2, hc[1] * hh2 - hsz / 2, hsz, hsz);
|
||
ctx.fill();
|
||
ctx.stroke();
|
||
}
|
||
ctx.restore();
|
||
}
|
||
else if (al.type === 'fill') {
|
||
ctx.strokeRect(al.x, al.y, al.w, al.h);
|
||
}
|
||
else if (al.type === 'paint') {
|
||
ctx.strokeRect(al.ox, al.oy, al.canvas.width, al.canvas.height);
|
||
}
|
||
ctx.setLineDash([]);
|
||
}
|
||
ctx.restore();
|
||
// 屏幕空间叠加层
|
||
// 预览区边框(提示“这里正在实时预览消除结果”)
|
||
if (preview.value) {
|
||
const pv = preview.value;
|
||
ctx.strokeStyle = '#2563eb';
|
||
ctx.lineWidth = 1.5;
|
||
ctx.setLineDash([5, 4]);
|
||
ctx.strokeRect(panX.value + pv.x * zoom.value, panY.value + pv.y * zoom.value, pv.w * zoom.value, pv.h * zoom.value);
|
||
ctx.setLineDash([]);
|
||
ctx.font = '11px sans-serif';
|
||
ctx.fillStyle = '#2563eb';
|
||
const pt = '预览(未应用)';
|
||
const ptw = ctx.measureText(pt).width + 10;
|
||
const pty = panY.value + pv.y * zoom.value - 17;
|
||
ctx.fillRect(panX.value + pv.x * zoom.value, pty < 0 ? panY.value + pv.y * zoom.value : pty, ptw, 15);
|
||
ctx.fillStyle = '#fff';
|
||
ctx.textBaseline = 'middle';
|
||
ctx.fillText(pt, panX.value + pv.x * zoom.value + 5, (pty < 0 ? panY.value + pv.y * zoom.value : pty) + 8);
|
||
}
|
||
// 智能消除笔拖动中的笔迹(红色半透明)
|
||
if (healOn && healCanvas) {
|
||
ctx.save();
|
||
ctx.globalAlpha = 0.55;
|
||
ctx.drawImage(healCanvas, panX.value, panY.value, docW.value * zoom.value, docH.value * zoom.value);
|
||
ctx.restore();
|
||
}
|
||
ctx.strokeStyle = '#d03050';
|
||
ctx.lineWidth = 1.5;
|
||
if (selection.value) {
|
||
const s = selection.value;
|
||
ctx.setLineDash([6, 4]);
|
||
ctx.strokeRect(panX.value + s.x * zoom.value, panY.value + s.y * zoom.value, s.w * zoom.value, s.h * zoom.value);
|
||
ctx.setLineDash([]);
|
||
ctx.fillStyle = 'rgba(208,48,80,0.12)';
|
||
ctx.fillRect(panX.value + s.x * zoom.value, panY.value + s.y * zoom.value, s.w * zoom.value, s.h * zoom.value);
|
||
}
|
||
if (dragRect.value) {
|
||
const d = dragRect.value;
|
||
ctx.setLineDash([6, 4]);
|
||
ctx.strokeStyle = tool.value === 'crop' ? '#2563eb' : '#d03050';
|
||
ctx.strokeRect(panX.value + d.x * zoom.value, panY.value + d.y * zoom.value, d.w * zoom.value, d.h * zoom.value);
|
||
ctx.setLineDash([]);
|
||
}
|
||
// OCR 框
|
||
for (const h of ocrHits.value) {
|
||
if (h.used) {
|
||
continue;
|
||
}
|
||
const selected = h.id === selHitId.value;
|
||
ctx.strokeStyle = selected ? '#2563eb' : '#d03050';
|
||
ctx.lineWidth = selected ? 2 : 1.2;
|
||
const hx = panX.value + h.x * zoom.value;
|
||
const hy = panY.value + h.y * zoom.value;
|
||
ctx.setLineDash([6, 4]);
|
||
ctx.strokeRect(hx, hy, h.w * zoom.value, h.h * zoom.value);
|
||
ctx.setLineDash([]);
|
||
const label = h.text.length > 14 ? `${h.text.slice(0, 14)}…` : h.text;
|
||
ctx.font = '11px sans-serif';
|
||
const tw = ctx.measureText(label).width + 8;
|
||
const ly = hy - 16 < 0 ? hy : hy - 16;
|
||
ctx.fillStyle = selected ? '#2563eb' : 'rgba(208,48,80,0.92)';
|
||
ctx.fillRect(hx, ly, tw, 15);
|
||
ctx.fillStyle = '#fff';
|
||
ctx.textBaseline = 'middle';
|
||
ctx.fillText(label, hx + 4, ly + 8);
|
||
}
|
||
// 画笔光圈
|
||
if (hover.value && (tool.value === 'brush' || tool.value === 'eraser')) {
|
||
ctx.beginPath();
|
||
ctx.arc(hover.value.x, hover.value.y, Math.max(2, (brushSize.value * zoom.value) / 2), 0, Math.PI * 2);
|
||
ctx.strokeStyle = 'rgba(255,255,255,0.9)';
|
||
ctx.lineWidth = 1;
|
||
ctx.stroke();
|
||
ctx.beginPath();
|
||
ctx.arc(hover.value.x, hover.value.y, Math.max(2, (brushSize.value * zoom.value) / 2) + 1, 0, Math.PI * 2);
|
||
ctx.strokeStyle = 'rgba(0,0,0,0.6)';
|
||
ctx.stroke();
|
||
}
|
||
}
|
||
|
||
function fit(): void {
|
||
const host = viewEl.value;
|
||
if (!host || !docW.value) {
|
||
return;
|
||
}
|
||
const z = Math.min((host.clientWidth - 32) / docW.value, (host.clientHeight - 32) / docH.value, 1);
|
||
zoom.value = Math.max(0.03, z);
|
||
panX.value = (host.clientWidth - docW.value * zoom.value) / 2;
|
||
panY.value = (host.clientHeight - docH.value * zoom.value) / 2;
|
||
scheduleRender();
|
||
}
|
||
|
||
function setZoom(z: number): void {
|
||
const host = viewEl.value;
|
||
const nz = Math.max(0.03, Math.min(32, z));
|
||
if (host) {
|
||
const cx = host.clientWidth / 2;
|
||
const cy = host.clientHeight / 2;
|
||
const dx = (cx - panX.value) / zoom.value;
|
||
const dy = (cy - panY.value) / zoom.value;
|
||
panX.value = cx - dx * nz;
|
||
panY.value = cy - dy * nz;
|
||
}
|
||
zoom.value = nz;
|
||
scheduleRender();
|
||
}
|
||
|
||
function onWheel(e: WheelEvent): void {
|
||
const host = viewEl.value!;
|
||
const rect = host.getBoundingClientRect();
|
||
const mx = e.clientX - rect.left;
|
||
const my = e.clientY - rect.top;
|
||
const dx = (mx - panX.value) / zoom.value;
|
||
const dy = (my - panY.value) / zoom.value;
|
||
const nz = Math.max(0.03, Math.min(32, zoom.value * (e.deltaY < 0 ? 1.15 : 1 / 1.15)));
|
||
panX.value = mx - dx * nz;
|
||
panY.value = my - dy * nz;
|
||
zoom.value = nz;
|
||
scheduleRender();
|
||
}
|
||
|
||
// ---------- 坐标 ----------
|
||
function toDoc(e: PointerEvent | MouseEvent): { x: number; y: number } {
|
||
const rect = viewEl.value!.getBoundingClientRect();
|
||
return {
|
||
x: (e.clientX - rect.left - panX.value) / zoom.value,
|
||
y: (e.clientY - rect.top - panY.value) / zoom.value,
|
||
};
|
||
}
|
||
|
||
// ---------- 选区 / 拖拽框 ----------
|
||
const selection = ref<{ x: number; y: number; w: number; h: number } | null>(null);
|
||
// 实时预览:消除结果先渲染到画布(不落图层),点「✓ 应用」才写入
|
||
const preview = ref<{ x: number; y: number; w: number; h: number; canvas: HTMLCanvasElement; label: string; hitId?: string } | null>(null);
|
||
// 智能消除笔(橡皮底图模式):拖动中的笔迹蒙版
|
||
let healCanvas: HTMLCanvasElement | null = null;
|
||
let healOn = false;
|
||
let healBBox = { x0: 0, y0: 0, x1: 0, y1: 0 };
|
||
let healLast: { x: number; y: number } | null = null;
|
||
const dragRect = ref<{ x: number; y: number; w: number; h: number } | null>(null);
|
||
let dragStart: { x: number; y: number } | null = null;
|
||
|
||
function normRect(a: { x: number; y: number }, b: { x: number; y: number }): { x: number; y: number; w: number; h: number } {
|
||
return { x: Math.round(Math.min(a.x, b.x)), y: Math.round(Math.min(a.y, b.y)), w: Math.round(Math.abs(b.x - a.x)), h: Math.round(Math.abs(b.y - a.y)) };
|
||
}
|
||
|
||
// ---------- 选区操作 ----------
|
||
function createPaintLayer(name: string, toTop = false): PaintLayer {
|
||
const c = document.createElement('canvas');
|
||
c.width = docW.value;
|
||
c.height = docH.value;
|
||
const pl: PaintLayer = { id: uid(), type: 'paint', name, visible: true, opacity: 100, ox: 0, oy: 0, canvas: c };
|
||
if (toTop) {
|
||
layers.value.push(pl); // 消除结果必须盖住底图和其上的文字/色块
|
||
}
|
||
else {
|
||
let idx = layers.value.findIndex(v => v.type === 'image');
|
||
if (idx < 0) {
|
||
idx = layers.value.length - 1;
|
||
}
|
||
layers.value.splice(idx + 1, 0, pl);
|
||
}
|
||
activeLayerId.value = pl.id;
|
||
return pl;
|
||
}
|
||
|
||
function ensurePaintLayer(name?: string): PaintLayer {
|
||
const l = layers.value.find(v => v.id === activeLayerId.value);
|
||
if (l && l.type === 'paint') {
|
||
return l;
|
||
}
|
||
return createPaintLayer(name ?? '画笔图层');
|
||
}
|
||
|
||
function addPaintLayer(): void {
|
||
const c = document.createElement('canvas');
|
||
c.width = docW.value;
|
||
c.height = docH.value;
|
||
const pl: PaintLayer = { id: uid(), type: 'paint', name: `画笔图层 ${layers.value.filter(v => v.type === 'paint').length + 1}`, visible: true, opacity: 100, ox: 0, oy: 0, canvas: c };
|
||
layers.value.push(pl);
|
||
activeLayerId.value = pl.id;
|
||
commit('新建画笔图层');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function addTextLayerAt(x: number, y: number): void {
|
||
const t = newText.value.trim() || '新文字';
|
||
const tl: TextLayer = { id: uid(), type: 'text', name: `文字「${t.slice(0, 8)}」`, visible: true, opacity: 100, text: t, x: Math.round(x), y: Math.round(y), size: fontSize.value, color: fontColor.value, bold: fontBold.value, rot: 0 };
|
||
layers.value.push(tl);
|
||
activeLayerId.value = tl.id;
|
||
commit('添加文字');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
// 文字模板套用:已选文字层→即时换样式;未选→以当前输入文字在画布上部居中新建
|
||
function applyTpl(t: TextTpl): void {
|
||
const style = {
|
||
color: t.color,
|
||
bold: t.bold ?? true,
|
||
grad: (t.grad ?? null) as [string, string] | null,
|
||
stroke: (t.stroke ?? null) as string | null,
|
||
strokeW: t.strokeW ?? null,
|
||
shadow: (t.shadow ?? null) as string | null,
|
||
badge: (t.badge ?? null) as string | null,
|
||
};
|
||
const al = activeLayer.value;
|
||
if (al && al.type === 'text') {
|
||
Object.assign(al, style);
|
||
commitProps(); // 实时生效并进历史(保留用户已输入内容)
|
||
return;
|
||
}
|
||
// 未选中文字层 → 按模板成套插入整组文案(主标题大、副标题依次递减,整体居中)
|
||
const ratios = [1, 0.62, 0.5, 0.42];
|
||
const base = fontSize.value;
|
||
let sizes = t.parts.map((_, i) => Math.max(10, Math.round(base * (ratios[Math.min(i, ratios.length - 1)]))));
|
||
const gap = Math.round(base * 0.18);
|
||
const totalOf = (ss: number[]) => ss.reduce((s, sz) => s + Math.round(sz * 1.3), 0) + gap * (t.parts.length - 1);
|
||
const avail = docH.value * 0.76;
|
||
let totalH = totalOf(sizes);
|
||
if (totalH > avail) {
|
||
const k = avail / totalH;
|
||
sizes = sizes.map(sz => Math.max(9, Math.round(sz * k)));
|
||
totalH = totalOf(sizes);
|
||
}
|
||
// 级联:新组放在已有文字层底边之下;空间不足则自动缩字号塞入(绝不叠到已有组上)
|
||
let maxY = 0;
|
||
for (const l of layers.value) {
|
||
if (l.type === 'text') {
|
||
maxY = Math.max(maxY, l.y + textMetrics(l).h);
|
||
}
|
||
}
|
||
const cascade = maxY > 0 ? maxY + gap : -1;
|
||
let y: number;
|
||
if (cascade > 0) {
|
||
const space = docH.value * 0.96 - cascade;
|
||
if (space < 26) {
|
||
y = Math.max(8, Math.round((docH.value - totalH) / 2.4)); // 极端无空间才回居中
|
||
}
|
||
else {
|
||
if (totalH > space) {
|
||
const k = space / totalH;
|
||
sizes = sizes.map(sz => Math.max(9, Math.round(sz * k)));
|
||
totalH = totalOf(sizes);
|
||
}
|
||
y = Math.round(Math.min(cascade, docH.value * 0.96 - totalH));
|
||
}
|
||
}
|
||
else {
|
||
y = Math.max(8, Math.round((docH.value - totalH) / 2.4));
|
||
}
|
||
let firstId = '';
|
||
t.parts.forEach((text, i) => {
|
||
const tl: TextLayer = {
|
||
id: uid(), type: 'text', name: `文字「${text.slice(0, 8)}」`,
|
||
visible: true, opacity: 100, text,
|
||
x: 0, y, size: sizes[i], rot: 0, ...style,
|
||
};
|
||
layers.value.push(tl);
|
||
const m = textMetrics(tl);
|
||
tl.x = Math.round((docW.value - m.w) / 2); // 每行独立居中
|
||
if (!firstId) {
|
||
firstId = tl.id;
|
||
}
|
||
y += Math.round(sizes[i] * 1.3) + gap;
|
||
});
|
||
activeLayerId.value = ''; // 不选中:可连续点模板插入多组;点中文字行后再点模板=换该行样式
|
||
if (tool.value !== 'text' && tool.value !== 'move') {
|
||
tool.value = 'move';
|
||
}
|
||
commit(`套用模板「${t.name}」(${t.parts.length}行)`);
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
|
||
|
||
function removeLayer(id: string): void {
|
||
const i = layers.value.findIndex(l => l.id === id);
|
||
if (i < 0 || layers.value[i].type === 'image') {
|
||
return;
|
||
}
|
||
layers.value.splice(i, 1);
|
||
if (activeLayerId.value === id) {
|
||
activeLayerId.value = layers.value[layers.value.length - 1]?.id ?? '';
|
||
}
|
||
commit('删除图层');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function moveLayer(id: string, dir: -1 | 1): void {
|
||
const i = layers.value.findIndex(l => l.id === id);
|
||
const j = i + dir;
|
||
if (i < 0 || j < 0 || j >= layers.value.length || layers.value[i].type === 'image' || layers.value[j].type === 'image') {
|
||
return;
|
||
}
|
||
const arr = layers.value;
|
||
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||
layers.value = [...arr];
|
||
commit('调整图层顺序');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
// 点击图层属性变更后的统一收尾
|
||
function onLayerPropChange(): void {
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
function commitProps(): void {
|
||
commit('修改图层属性');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
// ---------- 选区操作 ----------
|
||
function activePaintForEdit(): PaintLayer | null {
|
||
const al = activeLayer.value;
|
||
if (al && al.type === 'paint') {
|
||
return al;
|
||
}
|
||
return ensurePaintLayer();
|
||
}
|
||
|
||
function fillSelection(): void {
|
||
const s = selection.value;
|
||
if (!s || s.w < 1 || s.h < 1) {
|
||
return;
|
||
}
|
||
const pl = activePaintForEdit();
|
||
const ctx = pl.canvas.getContext('2d')!;
|
||
ctx.fillStyle = brushColor.value;
|
||
ctx.fillRect(s.x, s.y, s.w, s.h);
|
||
commit('填充选区');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
// 智能消除选区:框住文字/水印/杂物 → 从周边背景扩散重建,无需 OCR
|
||
function inpaintSelection(): void {
|
||
const s = selection.value;
|
||
if (!s || s.w < 4 || s.h < 4) {
|
||
emit('error', '请先框选要消除的区域(不小于 4×4)');
|
||
return;
|
||
}
|
||
const res = computeInpaint(s);
|
||
if (res) {
|
||
showPreview(res, '智能消除选区');
|
||
}
|
||
else {
|
||
emit('error', '选区内未检出可消除的内容(与背景一致),可改用填充/画笔');
|
||
}
|
||
}
|
||
|
||
function clearSelection(): void {
|
||
const s = selection.value;
|
||
if (!s || s.w < 1 || s.h < 1) {
|
||
return;
|
||
}
|
||
const al = activeLayer.value;
|
||
if (al && al.type === 'paint') {
|
||
al.canvas.getContext('2d')!.clearRect(s.x - al.ox, s.y - al.oy, s.w, s.h);
|
||
}
|
||
else {
|
||
const pl = activePaintForEdit();
|
||
pl.canvas.getContext('2d')!.clearRect(s.x - pl.ox, s.y - pl.oy, s.w, s.h);
|
||
}
|
||
commit('清除选区');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function applyCrop(): void {
|
||
const r = dragRect.value ?? selection.value;
|
||
if (!r || r.w < 8 || r.h < 8) {
|
||
emit('error', '请先框选不小于 8×8 的裁剪区域');
|
||
return;
|
||
}
|
||
docW.value = r.w;
|
||
docH.value = r.h;
|
||
if (baseCanvas) {
|
||
const c = document.createElement('canvas');
|
||
c.width = r.w;
|
||
c.height = r.h;
|
||
c.getContext('2d')!.drawImage(baseCanvas, -r.x, -r.y);
|
||
baseCanvas = c;
|
||
}
|
||
for (const l of layers.value) {
|
||
if (l.type === 'paint') {
|
||
const c = document.createElement('canvas');
|
||
c.width = r.w;
|
||
c.height = r.h;
|
||
c.getContext('2d')!.drawImage(l.canvas, -r.x, -r.y);
|
||
l.canvas = c;
|
||
l.ox = 0;
|
||
l.oy = 0;
|
||
}
|
||
else if (l.type === 'text') {
|
||
l.x -= r.x;
|
||
l.y -= r.y;
|
||
}
|
||
else if (l.type === 'fill') {
|
||
l.x -= r.x;
|
||
l.y -= r.y;
|
||
}
|
||
}
|
||
selection.value = null;
|
||
dragRect.value = null;
|
||
ensureComp();
|
||
commit('裁剪');
|
||
composite();
|
||
fit();
|
||
}
|
||
|
||
// ---------- 油漆桶 ----------
|
||
function floodFill(sx: number, sy: number): void {
|
||
sx = Math.round(sx);
|
||
sy = Math.round(sy);
|
||
if (sx < 0 || sy < 0 || sx >= docW.value || sy >= docH.value) {
|
||
return;
|
||
}
|
||
const w = docW.value;
|
||
const h = docH.value;
|
||
const src = compCanvas!.getContext('2d', { willReadFrequently: true })!.getImageData(0, 0, w, h);
|
||
const sd = src.data;
|
||
const si = (sy * w + sx) * 4;
|
||
const tr = sd[si];
|
||
const tg = sd[si + 1];
|
||
const tb = sd[si + 2];
|
||
const ta = sd[si + 3];
|
||
const tol = tolerance.value;
|
||
const fill = hexToRgb(brushColor.value);
|
||
const mask = new Uint8Array(w * h);
|
||
const stack: number[] = [sy * w + sx];
|
||
const matched = (p: number): boolean => {
|
||
const i = p * 4;
|
||
return Math.abs(sd[i] - tr) + Math.abs(sd[i + 1] - tg) + Math.abs(sd[i + 2] - tb) + Math.abs(sd[i + 3] - ta) <= tol * 4;
|
||
};
|
||
while (stack.length) {
|
||
const p = stack.pop()!;
|
||
if (mask[p]) {
|
||
continue;
|
||
}
|
||
if (!matched(p)) {
|
||
continue;
|
||
}
|
||
mask[p] = 1;
|
||
const x = p % w;
|
||
const y = (p / w) | 0;
|
||
if (x > 0) {
|
||
stack.push(p - 1);
|
||
}
|
||
if (x < w - 1) {
|
||
stack.push(p + 1);
|
||
}
|
||
if (y > 0) {
|
||
stack.push(p - w);
|
||
}
|
||
if (y < h - 1) {
|
||
stack.push(p + w);
|
||
}
|
||
}
|
||
const pl = activePaintForEdit();
|
||
const ctx = pl.canvas.getContext('2d')!;
|
||
const img = ctx.createImageData(w, h);
|
||
const d = img.data;
|
||
for (let p = 0; p < w * h; p++) {
|
||
if (mask[p]) {
|
||
const i = p * 4;
|
||
d[i] = fill.r;
|
||
d[i + 1] = fill.g;
|
||
d[i + 2] = fill.b;
|
||
d[i + 3] = 255;
|
||
}
|
||
}
|
||
const tmp = document.createElement('canvas');
|
||
tmp.width = w;
|
||
tmp.height = h;
|
||
tmp.getContext('2d')!.putImageData(img, 0, 0);
|
||
ctx.drawImage(tmp, pl.ox, pl.oy);
|
||
commit('油漆桶填充');
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function hexToRgb(hex: string): { r: number; g: number; b: number } {
|
||
const m = /^#?([0-9a-f]{6})$/i.exec(hex);
|
||
if (!m) {
|
||
return { r: 0, g: 0, b: 0 };
|
||
}
|
||
const n = Number.parseInt(m[1], 16);
|
||
return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };
|
||
}
|
||
|
||
// ---------- 画笔 ----------
|
||
let strokeLast: { x: number; y: number } | null = null;
|
||
let strokeDirty = false;
|
||
|
||
function paintSeg(ctx: CanvasRenderingContext2D, a: { x: number; y: number }, b: { x: number; y: number }): void {
|
||
ctx.lineCap = 'round';
|
||
ctx.lineJoin = 'round';
|
||
ctx.lineWidth = brushSize.value;
|
||
if (tool.value === 'eraser') {
|
||
ctx.globalCompositeOperation = 'destination-out';
|
||
ctx.strokeStyle = 'rgba(0,0,0,1)';
|
||
}
|
||
else {
|
||
ctx.globalCompositeOperation = 'source-over';
|
||
ctx.strokeStyle = brushColor.value;
|
||
}
|
||
ctx.beginPath();
|
||
ctx.moveTo(a.x, a.y);
|
||
ctx.lineTo(b.x, b.y);
|
||
ctx.stroke();
|
||
ctx.globalCompositeOperation = 'source-over';
|
||
}
|
||
|
||
// ---------- OCR ----------
|
||
interface OcrHit { id: string; text: string; box: number[][]; x: number; y: number; w: number; h: number; used: boolean }
|
||
const ocrHits = ref<OcrHit[]>([]);
|
||
const ocrBusy = ref(false);
|
||
const selHitId = ref<string | null>(null);
|
||
const hitText = ref('');
|
||
const selHit = computed(() => ocrHits.value.find(h => h.id === selHitId.value) ?? null);
|
||
|
||
// ---------- 无痕改字:原文字样式自动检测 ----------
|
||
interface HitStyle { size: number; color: string; bold: boolean; angle: number; cx: number; cy: number; bw: number; colorName: string }
|
||
const hitStyle = ref<HitStyle | null>(null);
|
||
|
||
// 从 OCR 框像素推断:角度(框顶边)、字号(垂直行高×0.82)、颜色(框内墨迹中位色)、粗细(笔画横向行程)
|
||
function detectTextStyle(hit: OcrHit): HitStyle | null {
|
||
if (!baseCanvas || !hit.box || hit.box.length < 4) {
|
||
return null;
|
||
}
|
||
try {
|
||
const box = hit.box.map((p: any) => [Number(p[0]), Number(p[1])]);
|
||
const [p0, p1, p2, p3] = box;
|
||
// 顶边角度(框点序:左上→右上→右下→左下),归一到 (-90, 90] 防倒置
|
||
let angle = (Math.atan2(p1[1] - p0[1], p1[0] - p0[0]) * 180) / Math.PI;
|
||
if (angle > 90) {
|
||
angle -= 180;
|
||
}
|
||
if (angle <= -90) {
|
||
angle += 180;
|
||
}
|
||
// 垂直行高(两横边中点距)与平均行宽
|
||
const midT = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];
|
||
const midB = [(p3[0] + p2[0]) / 2, (p3[1] + p2[1]) / 2];
|
||
const bh = Math.hypot(midB[0] - midT[0], midB[1] - midT[1]);
|
||
const bw = (Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) + Math.hypot(p2[0] - p3[0], p2[1] - p3[1])) / 2;
|
||
const cx = (p0[0] + p1[0] + p2[0] + p3[0]) / 4;
|
||
const cy = (p0[1] + p1[1] + p2[1] + p3[1]) / 4;
|
||
const size = Math.max(10, Math.round(bh * 0.82));
|
||
// 采样包围盒 → 局部坐标判内外圈
|
||
const xs = box.map((p: any) => p[0]);
|
||
const ys = box.map((p: any) => p[1]);
|
||
const x0 = Math.max(0, Math.floor(Math.min(...xs)));
|
||
const y0 = Math.max(0, Math.floor(Math.min(...ys)));
|
||
const x1 = Math.min(baseCanvas.width, Math.ceil(Math.max(...xs)));
|
||
const y1 = Math.min(baseCanvas.height, Math.ceil(Math.max(...ys)));
|
||
if (x1 - x0 < 4 || y1 - y0 < 4) {
|
||
return null;
|
||
}
|
||
const ctx = baseCanvas.getContext('2d', { willReadFrequently: true })!;
|
||
const d = ctx.getImageData(x0, y0, x1 - x0, y1 - y0).data;
|
||
const W = x1 - x0;
|
||
const a = (angle * Math.PI) / 180;
|
||
const cos = Math.cos(a);
|
||
const sin = Math.sin(a);
|
||
const ringR = Math.max(bw / 2, bh / 2) + bh * 0.5;
|
||
const ring: number[][] = [];
|
||
const ink: number[][] = [];
|
||
const inkGrid: { x: number; y: number; lx: number; ly: number; dist?: number }[] = [];
|
||
for (let py = 0; py < y1 - y0; py++) {
|
||
for (let px = 0; px < x1 - x0; px++) {
|
||
const ox = px + x0 + 0.5 - cx;
|
||
const oy = py + y0 + 0.5 - cy;
|
||
const lx = ox * cos + oy * sin;
|
||
const ly = -ox * sin + oy * cos;
|
||
const i = (py * W + px) * 4;
|
||
const c = [d[i], d[i + 1], d[i + 2]];
|
||
if (Math.abs(lx) <= bw / 2 && Math.abs(ly) <= bh / 2) {
|
||
ink.push(c);
|
||
inkGrid.push({ x: px, y: py, lx, ly });
|
||
}
|
||
else if (Math.abs(lx) <= ringR && Math.abs(ly) <= ringR) {
|
||
ring.push(c);
|
||
}
|
||
}
|
||
}
|
||
const med = (arr: number[], k: number) => {
|
||
const v = arr.map(c => c[k]).sort((p, q) => p - q);
|
||
return v[v.length >> 1];
|
||
};
|
||
const bg = ring.length > 8 ? [med(ring, 0), med(ring, 1), med(ring, 2)] : [128, 128, 128];
|
||
const dist = (c: number[]) => Math.hypot(c[0] - bg[0], c[1] - bg[1], c[2] - bg[2]);
|
||
const thr = 60;
|
||
// 网格补距离(此前只存坐标)
|
||
for (let gi = 0; gi < inkGrid.length; gi++) {
|
||
const i4 = (inkGrid[gi].y) * W + (inkGrid[gi].x);
|
||
const off = i4 * 4;
|
||
inkGrid[gi].dist = Math.hypot(d[off] - bg[0], d[off + 1] - bg[1], d[off + 2] - bg[2]);
|
||
}
|
||
const inks = ink.filter(c => dist(c) > thr);
|
||
let color = '#000000';
|
||
let bold = false;
|
||
let colorName = '深色';
|
||
if (inks.length >= 6 && inks.length / Math.max(1, ink.length) > 0.008) {
|
||
const tr = Math.round(med(inks, 0));
|
||
const tg = Math.round(med(inks, 1));
|
||
const tb = Math.round(med(inks, 2));
|
||
color = `#${[tr, tg, tb].map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||
const lum = 0.299 * tr + 0.587 * tg + 0.114 * tb;
|
||
const sat = Math.max(tr, tg, tb) - Math.min(tr, tg, tb);
|
||
colorName = sat < 45 && lum > 215 ? '白色' : lum < 70 ? '黑色' : sat < 45 ? '灰色' : '彩色';
|
||
// 粗细:中心行带内墨迹横向行程中位数 / 字号
|
||
const band = inkGrid.filter(g => Math.abs(g.ly) < bh * 0.14 && (g.dist ?? 0) > thr);
|
||
if (band.length > 10) {
|
||
const rows = new Map<number, number[]>();
|
||
for (const g of band) {
|
||
const k = Math.round(g.ly * 2);
|
||
if (!rows.has(k)) {
|
||
rows.set(k, []);
|
||
}
|
||
rows.get(k)!.push(g.x);
|
||
}
|
||
const runs: number[] = [];
|
||
for (const [, xs2] of rows) {
|
||
xs2.sort((m, n) => m - n);
|
||
let len = 1;
|
||
for (let i2 = 1; i2 < xs2.length; i2++) {
|
||
if (xs2[i2] === xs2[i2 - 1] + 1) {
|
||
len += 1;
|
||
}
|
||
else {
|
||
runs.push(len);
|
||
len = 1;
|
||
}
|
||
}
|
||
runs.push(len);
|
||
}
|
||
if (runs.length) {
|
||
runs.sort((m, n) => m - n);
|
||
const stroke = runs[runs.length >> 1];
|
||
bold = stroke / size > 0.11;
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
// 检不出墨迹:按背景明暗给默认字色
|
||
const bl = 0.299 * bg[0] + 0.587 * bg[1] + 0.114 * bg[2];
|
||
color = bl < 110 ? '#ffffff' : '#000000';
|
||
colorName = bl < 110 ? '白色(推测)' : '黑色(推测)';
|
||
}
|
||
return { size, color, bold, angle: Math.round(angle * 10) / 10, cx, cy, bw, colorName };
|
||
}
|
||
catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// 无痕改字的实时预览文字层(输入即所见)
|
||
function hitPreviewLayer(text: string): TextLayer | null {
|
||
const st = hitStyle.value;
|
||
if (!st) {
|
||
return null;
|
||
}
|
||
const tmp: TextLayer = { id: '__hitpv', type: 'text', name: '', visible: true, opacity: 100, text, x: 0, y: 0, size: st.size, color: st.color, bold: st.bold, rot: st.angle };
|
||
let m = textMetrics(tmp);
|
||
// 新字比原框宽太多 → 自动缩到框宽 1.15 倍内
|
||
if (m.w > st.bw * 1.15 && m.w > 0) {
|
||
tmp.size = Math.max(8, Math.round((st.bw * 1.15 * st.size) / m.w));
|
||
m = textMetrics(tmp);
|
||
}
|
||
tmp.x = Math.round(st.cx - m.w / 2);
|
||
tmp.y = Math.round(st.cy - m.h / 2);
|
||
return tmp;
|
||
}
|
||
|
||
async function runOcr(): Promise<void> {
|
||
if (!props.file) {
|
||
emit('error', '请先选择图片');
|
||
return;
|
||
}
|
||
ocrBusy.value = true;
|
||
try {
|
||
const form = new FormData();
|
||
form.append('image_file', props.file, props.file.name || 'image.png');
|
||
const res = await fetch('/api/ocr', { method: 'POST', body: form, headers: licenseHeaders('image-tools') });
|
||
if (!res.ok) {
|
||
throw new Error(res.status === 403 ? 'OCR 需要授权或试用' : `OCR 服务 HTTP ${res.status}`);
|
||
}
|
||
const data = await res.json().catch(() => ({}));
|
||
const hits: OcrHit[] = [];
|
||
for (const k of Object.keys(data)) {
|
||
const pts = data[k]?.dt_boxes;
|
||
if (!Array.isArray(pts) || pts.length < 4) {
|
||
continue;
|
||
}
|
||
const text = String(data[k]?.rec_txt ?? '').trim();
|
||
if (!text) {
|
||
continue;
|
||
}
|
||
const xs = pts.map((p: any) => Number(p[0]));
|
||
const ys = pts.map((p: any) => Number(p[1]));
|
||
const x = Math.min(...xs);
|
||
const y = Math.min(...ys);
|
||
hits.push({ id: `ocr-${k}`, text, box: pts, x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y, used: false });
|
||
}
|
||
ocrHits.value = hits;
|
||
if (!hits.length) {
|
||
emit('error', '未识别到文字,可截图更清晰后重试,或直接用文字工具加字');
|
||
}
|
||
scheduleRender();
|
||
}
|
||
catch (e: any) {
|
||
emit('error', `识别失败:${e?.message ?? e}`);
|
||
}
|
||
finally {
|
||
ocrBusy.value = false;
|
||
}
|
||
}
|
||
|
||
// 采样文字框外圈中位色作为覆盖底色
|
||
function sampleBoxColor(box: { x: number; y: number; w: number; h: number }): string {
|
||
if (!baseCanvas) {
|
||
return '#ffffff';
|
||
}
|
||
try {
|
||
const ctx = baseCanvas.getContext('2d', { willReadFrequently: true })!;
|
||
const pad = Math.max(3, Math.round(Math.min(box.w, box.h) * 0.35));
|
||
const sx = Math.max(0, Math.round(box.x - pad));
|
||
const sy = Math.max(0, Math.round(box.y - pad));
|
||
const sw = Math.min(baseCanvas.width - sx, Math.round(box.w + pad * 2));
|
||
const sh = Math.min(baseCanvas.height - sy, Math.round(box.h + pad * 2));
|
||
if (sw <= 0 || sh <= 0) {
|
||
return '#ffffff';
|
||
}
|
||
const d = ctx.getImageData(sx, sy, sw, sh).data;
|
||
const rs: number[] = [];
|
||
const gs: number[] = [];
|
||
const bs: number[] = [];
|
||
for (let py = 0; py < sh; py++) {
|
||
for (let px = 0; px < sw; px++) {
|
||
const ix = sx + px;
|
||
const iy = sy + py;
|
||
if (ix >= box.x && ix < box.x + box.w && iy >= box.y && iy < box.y + box.h) {
|
||
continue;
|
||
}
|
||
const i = (py * sw + px) * 4;
|
||
rs.push(d[i]);
|
||
gs.push(d[i + 1]);
|
||
bs.push(d[i + 2]);
|
||
}
|
||
}
|
||
if (!rs.length) {
|
||
return '#ffffff';
|
||
}
|
||
const med = (a: number[]) => {
|
||
a.sort((p, q) => p - q);
|
||
return a[a.length >> 1];
|
||
};
|
||
return `rgb(${med(rs)}, ${med(gs)}, ${med(bs)})`;
|
||
}
|
||
catch {
|
||
return '#ffffff';
|
||
}
|
||
}
|
||
|
||
// 无痕改字:先用 inpaint 无缝重建背景(擦掉原字),再按检测样式重绘新字;一步历史可整体撤销
|
||
function applyHitReplace(): void {
|
||
const hit = selHit.value;
|
||
if (!hit || hit.used) {
|
||
return;
|
||
}
|
||
const content = hitText.value.trim() || hit.text;
|
||
const st = hitStyle.value ?? detectTextStyle(hit);
|
||
cancelPreview(); // 替换是另一条路径,先撤掉消除预览
|
||
// 1) 无缝擦除原字(背景扩散重建,非色块覆盖)
|
||
const res = computeInpaint(hitInpaintRect(hit));
|
||
if (res) {
|
||
const pl = createPaintLayer('智能消除', true);
|
||
pl.canvas.getContext('2d')!.drawImage(res.canvas, res.x, res.y);
|
||
}
|
||
// 2) 按检测样式重绘新字(字号/颜色/粗细/角度与原字一致,居中对齐原框)
|
||
let tl: TextLayer;
|
||
if (st) {
|
||
const tmp: TextLayer = { id: uid(), type: 'text', name: `文字「${content.slice(0, 8)}」`, visible: true, opacity: 100, text: content, x: 0, y: 0, size: st.size, color: st.color, bold: st.bold, rot: st.angle };
|
||
let m = textMetrics(tmp);
|
||
if (m.w > st.bw * 1.15 && m.w > 0) {
|
||
tmp.size = Math.max(8, Math.round((st.bw * 1.15 * st.size) / m.w)); // 新字过长自动缩号
|
||
m = textMetrics(tmp);
|
||
}
|
||
tmp.x = Math.round(st.cx - m.w / 2);
|
||
tmp.y = Math.round(st.cy - m.h / 2);
|
||
tl = tmp;
|
||
}
|
||
else {
|
||
// 检测失败退回旧路径:色块覆盖 + 黑字
|
||
const color = sampleBoxColor(hit);
|
||
const padX = Math.max(1, Math.round(hit.w * 0.02));
|
||
const padY = Math.max(1, Math.round(hit.h * 0.08));
|
||
const fl: FillLayer = { id: uid(), type: 'fill', name: '擦除色块', visible: true, opacity: 100, x: Math.max(0, hit.x - padX), y: Math.max(0, hit.y - padY), w: hit.w + padX * 2, h: hit.h + padY * 2, color };
|
||
layers.value.push(fl);
|
||
tl = { id: uid(), type: 'text', name: `文字「${content.slice(0, 8)}」`, visible: true, opacity: 100, text: content, x: hit.x, y: hit.y + hit.h * 0.06, size: Math.max(10, Math.round(hit.h * 0.82)), color: '#000000', bold: false, rot: 0 };
|
||
}
|
||
layers.value.push(tl);
|
||
activeLayerId.value = tl.id;
|
||
hit.used = true;
|
||
selHitId.value = null;
|
||
hitText.value = '';
|
||
hitStyle.value = null;
|
||
commit(`无痕改字「${content}」`);
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function applyHitErase(): void {
|
||
const hit = selHit.value;
|
||
if (!hit || hit.used) {
|
||
return;
|
||
}
|
||
// 已有该框的实时预览 → 直接应用;否则计算并立即应用(兼容按钮直点)
|
||
if (preview.value && preview.value.hitId === hit.id) {
|
||
applyPreview();
|
||
return;
|
||
}
|
||
const rect = hitInpaintRect(hit);
|
||
const res = computeInpaint(rect);
|
||
if (!res) {
|
||
emit('error', '该框内未检出可消除的文字');
|
||
return;
|
||
}
|
||
showPreview(res, 'OCR 消除文字', hit.id);
|
||
applyPreview();
|
||
}
|
||
|
||
// OCR 文字框 → 消除用矩形(四周少量外扩)
|
||
function hitInpaintRect(hit: OcrHit): { x: number; y: number; w: number; h: number } {
|
||
const padX = Math.max(2, Math.round(hit.w * 0.04));
|
||
const padY = Math.max(2, Math.round(hit.h * 0.1));
|
||
const rect = {
|
||
x: Math.max(0, hit.x - padX),
|
||
y: Math.max(0, hit.y - padY),
|
||
w: Math.min(docW.value, hit.w + padX * 2),
|
||
h: Math.min(docH.value, hit.h + padY * 2),
|
||
};
|
||
rect.w = Math.min(rect.w, docW.value - rect.x);
|
||
rect.h = Math.min(rect.h, docH.value - rect.y);
|
||
return rect;
|
||
}
|
||
|
||
// ---------- 智能消除(inpainting) ----------
|
||
// 纯计算:识别文字笔画(或用外部笔迹蒙版),从周边已知像素扩散重建该区域,
|
||
// 返回只含重建像素的透明画布(不写图层),供「实时预览」和「应用」共用。
|
||
function computeInpaint(rect: { x: number; y: number; w: number; h: number }, strokeMask?: Uint8Array | null):
|
||
{ x: number; y: number; w: number; h: number; canvas: HTMLCanvasElement } | null {
|
||
if (!compCanvas || rect.w < 2 || rect.h < 2) {
|
||
return null;
|
||
}
|
||
const rw = Math.round(rect.w);
|
||
const rh = Math.round(rect.h);
|
||
const rx = Math.round(rect.x);
|
||
const ry = Math.round(rect.y);
|
||
const src = compCanvas.getContext('2d', { willReadFrequently: true })!.getImageData(rx, ry, rw, rh);
|
||
const d = src.data;
|
||
const mask = new Uint8Array(rw * rh);
|
||
let unknown = 0;
|
||
if (strokeMask && strokeMask.length === rw * rh) {
|
||
// 外部笔迹蒙版(智能消除笔):涂哪消哪
|
||
for (let p = 0; p < rw * rh; p++) {
|
||
if (strokeMask[p]) {
|
||
mask[p] = 1;
|
||
unknown++;
|
||
}
|
||
}
|
||
}
|
||
else {
|
||
// 自动检测:取区域外圈 2px 环带中位色作背景参考,差异大的判为笔画
|
||
const rs: number[] = [];
|
||
const gs: number[] = [];
|
||
const bs: number[] = [];
|
||
for (let y = 0; y < rh; y++) {
|
||
for (let x = 0; x < rw; x++) {
|
||
const onRing = x < 2 || y < 2 || x >= rw - 2 || y >= rh - 2;
|
||
if (!onRing) {
|
||
continue;
|
||
}
|
||
const i = (y * rw + x) * 4;
|
||
rs.push(d[i]);
|
||
gs.push(d[i + 1]);
|
||
bs.push(d[i + 2]);
|
||
}
|
||
}
|
||
if (!rs.length) {
|
||
return null;
|
||
}
|
||
const med = (a: number[]) => {
|
||
a.sort((p, q) => p - q);
|
||
return a[a.length >> 1];
|
||
};
|
||
const bgR = med(rs);
|
||
const bgG = med(gs);
|
||
const bgB = med(bs);
|
||
const thr = 42;
|
||
for (let y = 0; y < rh; y++) {
|
||
for (let x = 0; x < rw; x++) {
|
||
const p = y * rw + x;
|
||
const i = p * 4;
|
||
const dist = Math.abs(d[i] - bgR) + Math.abs(d[i + 1] - bgG) + Math.abs(d[i + 2] - bgB);
|
||
if (dist > thr) {
|
||
mask[p] = 1;
|
||
unknown++;
|
||
}
|
||
}
|
||
}
|
||
if (!unknown) {
|
||
return null; // 没检出文字
|
||
}
|
||
}
|
||
// 掩码向外扩 1px,覆盖抗锯齿边缘(带边界检查)
|
||
const grown = mask.slice();
|
||
for (let y = 0; y < rh; y++) {
|
||
for (let x = 0; x < rw; x++) {
|
||
const p = y * rw + x;
|
||
if (mask[p]) {
|
||
continue;
|
||
}
|
||
if ((x > 0 && mask[p - 1]) || (x < rw - 1 && mask[p + 1]) || (y > 0 && mask[p - rw]) || (y < rh - 1 && mask[p + rw])) {
|
||
grown[p] = 1;
|
||
unknown++;
|
||
}
|
||
}
|
||
}
|
||
// 扩散重建:未知像素反复取四邻均值(交替扫描消偏置;大区域降迭代防卡顿)
|
||
const buf = new Float32Array(rw * rh * 3);
|
||
for (let p = 0; p < rw * rh; p++) {
|
||
const i = p * 4;
|
||
buf[p * 3] = d[i];
|
||
buf[p * 3 + 1] = d[i + 1];
|
||
buf[p * 3 + 2] = d[i + 2];
|
||
}
|
||
const budget = Math.min(500, Math.max(rw, rh) * 2);
|
||
const iters = Math.min(budget, Math.max(40, Math.floor(12_000_000 / Math.max(1, unknown))));
|
||
for (let it = 0; it < iters; it++) {
|
||
const rev = it % 2 === 1;
|
||
for (let yy = 0; yy < rh; yy++) {
|
||
const y = rev ? rh - 1 - yy : yy;
|
||
for (let xx = 0; xx < rw; xx++) {
|
||
const x = rev ? rw - 1 - xx : xx;
|
||
const p = y * rw + x;
|
||
if (!grown[p]) {
|
||
continue;
|
||
}
|
||
let sr = 0;
|
||
let sg = 0;
|
||
let sb = 0;
|
||
let c = 0;
|
||
if (x > 0) {
|
||
const q = (p - 1) * 3;
|
||
sr += buf[q];
|
||
sg += buf[q + 1];
|
||
sb += buf[q + 2];
|
||
c++;
|
||
}
|
||
if (x < rw - 1) {
|
||
const q = (p + 1) * 3;
|
||
sr += buf[q];
|
||
sg += buf[q + 1];
|
||
sb += buf[q + 2];
|
||
c++;
|
||
}
|
||
if (y > 0) {
|
||
const q = (p - rw) * 3;
|
||
sr += buf[q];
|
||
sg += buf[q + 1];
|
||
sb += buf[q + 2];
|
||
c++;
|
||
}
|
||
if (y < rh - 1) {
|
||
const q = (p + rw) * 3;
|
||
sr += buf[q];
|
||
sg += buf[q + 1];
|
||
sb += buf[q + 2];
|
||
c++;
|
||
}
|
||
if (c) {
|
||
buf[p * 3] = sr / c;
|
||
buf[p * 3 + 1] = sg / c;
|
||
buf[p * 3 + 2] = sb / c;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// 只保留重建像素,其余透明
|
||
const out = new ImageData(rw, rh);
|
||
const od = out.data;
|
||
for (let p = 0; p < rw * rh; p++) {
|
||
if (!grown[p]) {
|
||
continue;
|
||
}
|
||
const i = p * 4;
|
||
od[i] = Math.max(0, Math.min(255, Math.round(buf[p * 3])));
|
||
od[i + 1] = Math.max(0, Math.min(255, Math.round(buf[p * 3 + 1])));
|
||
od[i + 2] = Math.max(0, Math.min(255, Math.round(buf[p * 3 + 2])));
|
||
od[i + 3] = 255;
|
||
}
|
||
const tmp = document.createElement('canvas');
|
||
tmp.width = rw;
|
||
tmp.height = rh;
|
||
tmp.getContext('2d')!.putImageData(out, 0, 0);
|
||
return { x: rx, y: ry, w: rw, h: rh, canvas: tmp };
|
||
}
|
||
|
||
// 实时预览:把计算结果显示在画布上(不写图层),等用户确认
|
||
function showPreview(res: { x: number; y: number; w: number; h: number; canvas: HTMLCanvasElement }, label: string, hitId?: string): void {
|
||
preview.value = hitId ? { ...res, label, hitId } : { ...res, label };
|
||
scheduleRender();
|
||
}
|
||
|
||
function cancelPreview(): void {
|
||
if (!preview.value) {
|
||
return;
|
||
}
|
||
preview.value = null;
|
||
scheduleRender();
|
||
}
|
||
|
||
// 应用预览:写入「智能消除」画笔层并进历史
|
||
function applyPreview(): void {
|
||
const pv = preview.value;
|
||
if (!pv) {
|
||
return;
|
||
}
|
||
const pl = createPaintLayer('智能消除', true);
|
||
pl.canvas.getContext('2d')!.drawImage(pv.canvas, pv.x, pv.y);
|
||
const hitId = pv.hitId;
|
||
if (hitId) {
|
||
const hit = ocrHits.value.find(h => h.id === hitId);
|
||
if (hit) {
|
||
hit.used = true;
|
||
}
|
||
if (selHitId.value === hitId) {
|
||
selHitId.value = null;
|
||
hitText.value = '';
|
||
hitStyle.value = null;
|
||
}
|
||
}
|
||
preview.value = null;
|
||
commit(pv.label);
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
|
||
function ocrHitTest(dx: number, dy: number): OcrHit | null {
|
||
for (const h of ocrHits.value) {
|
||
if (!h.used && dx >= h.x - 3 && dx <= h.x + h.w + 3 && dy >= h.y - 3 && dy <= h.y + h.h + 3) {
|
||
return h;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// ---------- 指针交互 ----------
|
||
let panning = false;
|
||
let panStart = { x: 0, y: 0, px: 0, py: 0 };
|
||
let moving: { layer: TextLayer | FillLayer | PaintLayer; offX: number; offY: number } | null = null;
|
||
let rotating: TextLayer | null = null; // 旋转手柄拖动中
|
||
let resizing: { layer: TextLayer; startDist: number; startSize: number } | null = null; // 四角缩放手柄拖动中
|
||
let spaceDown = false;
|
||
|
||
function layerHitTest(dx: number, dy: number): TextLayer | FillLayer | PaintLayer | null {
|
||
for (let i = layers.value.length - 1; i >= 0; i--) {
|
||
const l = layers.value[i];
|
||
if (!l.visible || l.type === 'image') {
|
||
continue;
|
||
}
|
||
if (l.type === 'text') {
|
||
if (textHitTest(l, dx, dy)) {
|
||
return l;
|
||
}
|
||
}
|
||
else if (l.type === 'fill') {
|
||
if (dx >= l.x && dx <= l.x + l.w && dy >= l.y && dy <= l.y + l.h) {
|
||
return l;
|
||
}
|
||
}
|
||
}
|
||
const al = activeLayer.value;
|
||
if (al && al.type === 'paint') {
|
||
return al;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function onDown(e: PointerEvent): void {
|
||
(e.target as HTMLElement).setPointerCapture?.(e.pointerId);
|
||
const p = toDoc(e);
|
||
// 1) OCR 框优先
|
||
const oh = ocrHitTest(p.x, p.y);
|
||
if (oh) {
|
||
selHitId.value = oh.id;
|
||
hitText.value = '';
|
||
hitStyle.value = detectTextStyle(oh); // 自动检测原文字样式(角度/字号/颜色/粗细)
|
||
// 点框即预览:文字立刻“消失”,满意点✓应用,不满意可换字或取消
|
||
cancelPreview();
|
||
const res = computeInpaint(hitInpaintRect(oh));
|
||
if (res) {
|
||
showPreview(res, 'OCR 消除文字', oh.id);
|
||
}
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
// 2) 空格或抓手 → 平移
|
||
if (tool.value === 'hand' || spaceDown || e.button === 1) {
|
||
panning = true;
|
||
panStart = { x: e.clientX, y: e.clientY, px: panX.value, py: panY.value };
|
||
return;
|
||
}
|
||
if (tool.value === 'move') {
|
||
// 优先:旋转手柄命中(仅当前选中文字层)
|
||
const al0 = activeLayer.value;
|
||
if (al0 && al0.type === 'text') {
|
||
const hp = textHandlePos(al0);
|
||
if (Math.hypot(p.x - hp.x, p.y - hp.y) <= 12 / zoom.value) {
|
||
rotating = al0;
|
||
return;
|
||
}
|
||
// 四角缩放手柄:拖动直接调字号(以文字中心为锚点)
|
||
for (const cp of textCornerPositions(al0)) {
|
||
if (Math.hypot(p.x - cp.x, p.y - cp.y) <= 10 / zoom.value) {
|
||
const cc = textCenter(al0);
|
||
resizing = { layer: al0, startDist: Math.max(10, Math.hypot(p.x - cc.x, p.y - cc.y)), startSize: al0.size };
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
const lh = layerHitTest(p.x, p.y);
|
||
if (lh) {
|
||
activeLayerId.value = lh.id;
|
||
const off = lh.type === 'paint' ? { x: p.x - lh.ox, y: p.y - lh.oy } : { x: p.x - lh.x, y: p.y - lh.y };
|
||
moving = { layer: lh, offX: off.x, offY: off.y };
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
// 空白处点击 → 清除选区
|
||
selection.value = null;
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (tool.value === 'marquee' || tool.value === 'crop') {
|
||
dragStart = p;
|
||
dragRect.value = { x: p.x, y: p.y, w: 0, h: 0 };
|
||
if (tool.value === 'marquee') {
|
||
selection.value = null;
|
||
cancelPreview();
|
||
}
|
||
return;
|
||
}
|
||
if (tool.value === 'brush' || tool.value === 'eraser') {
|
||
const al = activeLayer.value;
|
||
if (tool.value === 'eraser' && (!al || al.type !== 'paint')) {
|
||
// 智能消除笔:直接在底图/文字/色块上涂,松手即从周边背景重建
|
||
cancelPreview();
|
||
healOn = true;
|
||
healCanvas = document.createElement('canvas');
|
||
healCanvas.width = docW.value;
|
||
healCanvas.height = docH.value;
|
||
healLast = { x: p.x, y: p.y };
|
||
healBBox = { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
|
||
const hctx = healCanvas.getContext('2d')!;
|
||
hctx.fillStyle = '#fff';
|
||
hctx.beginPath();
|
||
hctx.arc(p.x, p.y, Math.max(1, brushSize.value / 2), 0, Math.PI * 2);
|
||
hctx.fill();
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
const pl = ensurePaintLayer();
|
||
const ctx = pl.canvas.getContext('2d')!;
|
||
strokeLast = { x: p.x - pl.ox, y: p.y - pl.oy };
|
||
paintSeg(ctx, strokeLast, strokeLast);
|
||
strokeDirty = true;
|
||
composite();
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (tool.value === 'text') {
|
||
addTextLayerAt(p.x, p.y);
|
||
return;
|
||
}
|
||
if (tool.value === 'fill') {
|
||
floodFill(p.x, p.y);
|
||
return;
|
||
}
|
||
if (tool.value === 'eyedropper') {
|
||
const d = compCanvas!.getContext('2d', { willReadFrequently: true })!.getImageData(Math.round(p.x), Math.round(p.y), 1, 1).data;
|
||
brushColor.value = `#${[d[0], d[1], d[2]].map(v => v.toString(16).padStart(2, '0')).join('')}`;
|
||
return;
|
||
}
|
||
}
|
||
|
||
function onMove(e: PointerEvent): void {
|
||
const p = toDoc(e);
|
||
if (panning) {
|
||
panX.value = panStart.px + (e.clientX - panStart.x);
|
||
panY.value = panStart.py + (e.clientY - panStart.y);
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (resizing) {
|
||
const l = resizing.layer;
|
||
const c = textCenter(l);
|
||
const d = Math.hypot(p.x - c.x, p.y - c.y);
|
||
const ratio = d / resizing.startDist;
|
||
const ns = Math.max(6, Math.min(600, Math.round(resizing.startSize * ratio)));
|
||
if (ns !== l.size) {
|
||
l.size = ns;
|
||
const m = textMetrics(l);
|
||
l.x = Math.round(c.x - m.w / 2); // 锚定文字中心:只变大小不漂移
|
||
l.y = Math.round(c.y - m.h / 2);
|
||
fontSize.value = ns; // 属性面板字号同步
|
||
composite();
|
||
scheduleRender();
|
||
}
|
||
return;
|
||
}
|
||
if (rotating) {
|
||
const c = textCenter(rotating);
|
||
let ang = (Math.atan2(p.y - c.y, p.x - c.x) * 180) / Math.PI + 90;
|
||
if (e.shiftKey) {
|
||
ang = Math.round(ang / 15) * 15; // Shift 吸附 15°
|
||
}
|
||
rotating.rot = Math.round(ang * 10) / 10;
|
||
composite(); // 实时重绘:拖动即看到文字跟着转
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (moving) {
|
||
const l = moving.layer;
|
||
const nx = Math.round(p.x - moving.offX);
|
||
const ny = Math.round(p.y - moving.offY);
|
||
if (l.type === 'paint') {
|
||
l.ox = nx;
|
||
l.oy = ny;
|
||
}
|
||
else {
|
||
l.x = nx;
|
||
l.y = ny;
|
||
}
|
||
composite();
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (healOn && healCanvas && healLast) {
|
||
const hctx = healCanvas.getContext('2d')!;
|
||
hctx.strokeStyle = '#fff';
|
||
hctx.lineWidth = Math.max(1, brushSize.value);
|
||
hctx.lineCap = 'round';
|
||
hctx.lineJoin = 'round';
|
||
hctx.beginPath();
|
||
hctx.moveTo(healLast.x, healLast.y);
|
||
hctx.lineTo(p.x, p.y);
|
||
hctx.stroke();
|
||
healLast = { x: p.x, y: p.y };
|
||
healBBox.x0 = Math.min(healBBox.x0, p.x);
|
||
healBBox.y0 = Math.min(healBBox.y0, p.y);
|
||
healBBox.x1 = Math.max(healBBox.x1, p.x);
|
||
healBBox.y1 = Math.max(healBBox.y1, p.y);
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (dragStart) {
|
||
dragRect.value = normRect(dragStart, p);
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (strokeLast && (tool.value === 'brush' || tool.value === 'eraser')) {
|
||
const al = activeLayer.value as PaintLayer | null;
|
||
if (al && al.type === 'paint') {
|
||
const ctx = al.canvas.getContext('2d')!;
|
||
const np = { x: p.x - al.ox, y: p.y - al.oy };
|
||
paintSeg(ctx, strokeLast, np);
|
||
strokeLast = np;
|
||
composite();
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
}
|
||
// 悬停光圈
|
||
const rect = viewEl.value!.getBoundingClientRect();
|
||
hover.value = { x: e.clientX - rect.left, y: e.clientY - rect.top };
|
||
if (tool.value === 'brush' || tool.value === 'eraser') {
|
||
scheduleRender();
|
||
}
|
||
}
|
||
|
||
function onUp(): void {
|
||
if (panning) {
|
||
panning = false;
|
||
return;
|
||
}
|
||
if (healOn && healCanvas) {
|
||
// 松手即消除:笔迹作蒙版,笔迹包围盒内从周边背景重建并立即应用
|
||
healOn = false;
|
||
healLast = null;
|
||
const pad = brushSize.value / 2 + 4;
|
||
const x0 = Math.max(0, Math.floor(healBBox.x0 - pad));
|
||
const y0 = Math.max(0, Math.floor(healBBox.y0 - pad));
|
||
const x1 = Math.min(docW.value, Math.ceil(healBBox.x1 + pad));
|
||
const y1 = Math.min(docH.value, Math.ceil(healBBox.y1 + pad));
|
||
const w = x1 - x0;
|
||
const h = y1 - y0;
|
||
const hc = healCanvas;
|
||
healCanvas = null;
|
||
if (w >= 4 && h >= 4) {
|
||
const img = hc.getContext('2d')!.getImageData(x0, y0, w, h);
|
||
const mask = new Uint8Array(w * h);
|
||
for (let i = 0; i < w * h; i++) {
|
||
mask[i] = img.data[i * 4 + 3] > 0 ? 1 : 0;
|
||
}
|
||
const res = computeInpaint({ x: x0, y: y0, w, h }, mask);
|
||
if (res) {
|
||
showPreview(res, '智能消除笔');
|
||
applyPreview(); // 松手立即生效 = 实时效果
|
||
}
|
||
}
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (resizing) {
|
||
const ns = resizing.layer.size;
|
||
resizing = null;
|
||
commit(`缩放文字 ${ns}px`);
|
||
return;
|
||
}
|
||
if (rotating) {
|
||
const r = Math.round(rotating.rot % 360);
|
||
rotating = null;
|
||
commit(`旋转文字 ${r}°`);
|
||
return;
|
||
}
|
||
if (moving) {
|
||
moving = null;
|
||
commit('移动图层');
|
||
return;
|
||
}
|
||
if (dragStart && dragRect.value) {
|
||
const r = dragRect.value;
|
||
dragStart = null;
|
||
if (r.w >= 4 && r.h >= 4) {
|
||
if (tool.value === 'marquee') {
|
||
selection.value = r;
|
||
// 松手即算:实时显示消除后的效果,用户确认后才落图层
|
||
const res = computeInpaint(r);
|
||
if (res) {
|
||
showPreview(res, '智能消除选区');
|
||
}
|
||
else {
|
||
preview.value = null;
|
||
}
|
||
}
|
||
// crop 保留 dragRect 供「应用裁剪」
|
||
}
|
||
else {
|
||
dragRect.value = null;
|
||
}
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (strokeLast) {
|
||
strokeLast = null;
|
||
if (strokeDirty) {
|
||
strokeDirty = false;
|
||
commit(tool.value === 'eraser' ? '橡皮擦除' : '画笔涂抹');
|
||
}
|
||
}
|
||
}
|
||
|
||
function onKeyDown(e: KeyboardEvent): void {
|
||
const t = e.target as HTMLElement;
|
||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) {
|
||
return;
|
||
}
|
||
const k = e.key.toLowerCase();
|
||
if ((e.ctrlKey || e.metaKey) && k === 'z' && !e.shiftKey) {
|
||
e.preventDefault();
|
||
undo();
|
||
return;
|
||
}
|
||
if ((e.ctrlKey || e.metaKey) && (k === 'y' || (k === 'z' && e.shiftKey))) {
|
||
e.preventDefault();
|
||
redo();
|
||
return;
|
||
}
|
||
if (e.ctrlKey || e.metaKey) {
|
||
return;
|
||
}
|
||
if (e.code === 'Space') {
|
||
spaceDown = true;
|
||
e.preventDefault();
|
||
scheduleRender();
|
||
return;
|
||
}
|
||
if (k === 'v') {
|
||
tool.value = 'move';
|
||
}
|
||
else if (k === 'm') {
|
||
tool.value = 'marquee';
|
||
}
|
||
else if (k === 'b') {
|
||
tool.value = 'brush';
|
||
}
|
||
else if (k === 'e') {
|
||
tool.value = 'eraser';
|
||
}
|
||
else if (k === 't') {
|
||
tool.value = 'text';
|
||
}
|
||
else if (k === 'g') {
|
||
tool.value = 'fill';
|
||
}
|
||
else if (k === 'i') {
|
||
tool.value = 'eyedropper';
|
||
}
|
||
else if (k === 'c') {
|
||
tool.value = 'crop';
|
||
}
|
||
else if (k === 'h') {
|
||
tool.value = 'hand';
|
||
}
|
||
else if (k === '[') {
|
||
brushSize.value = Math.max(1, brushSize.value - 4);
|
||
}
|
||
else if (k === ']') {
|
||
brushSize.value = Math.min(200, brushSize.value + 4);
|
||
}
|
||
else if (k === '0') {
|
||
fit();
|
||
}
|
||
else if (k === '1') {
|
||
setZoom(1);
|
||
}
|
||
else if (e.key === 'Delete' || e.key === 'Backspace') {
|
||
e.preventDefault();
|
||
if (selection.value) {
|
||
clearSelection();
|
||
}
|
||
else if (activeLayer.value && activeLayer.value.type !== 'image') {
|
||
removeLayer(activeLayerId.value);
|
||
}
|
||
}
|
||
else if (e.key === 'Escape') {
|
||
selection.value = null;
|
||
dragRect.value = null;
|
||
selHitId.value = null;
|
||
hitStyle.value = null;
|
||
cancelPreview();
|
||
scheduleRender();
|
||
}
|
||
}
|
||
|
||
function onKeyUp(e: KeyboardEvent): void {
|
||
if (e.code === 'Space') {
|
||
spaceDown = false;
|
||
scheduleRender();
|
||
}
|
||
}
|
||
|
||
// ---------- 导出 ----------
|
||
function exportDoc(): Promise<{ blob: Blob; detail: string; w: number; h: number }> {
|
||
return new Promise((resolve, reject) => {
|
||
if (!docW.value || !compCanvas) {
|
||
reject(new Error('还没有加载图片'));
|
||
return;
|
||
}
|
||
if (preview.value) {
|
||
applyPreview(); // 画布上看到的预览必须进成品(所见即所得)
|
||
}
|
||
composite();
|
||
const keepPng = props.file.type === 'image/png';
|
||
const out = document.createElement('canvas');
|
||
out.width = docW.value;
|
||
out.height = docH.value;
|
||
const ctx = out.getContext('2d')!;
|
||
if (!keepPng) {
|
||
ctx.fillStyle = '#ffffff';
|
||
ctx.fillRect(0, 0, docW.value, docH.value);
|
||
}
|
||
ctx.drawImage(compCanvas, 0, 0);
|
||
const mime = keepPng ? 'image/png' : 'image/jpeg';
|
||
out.toBlob((b) => {
|
||
if (!b) {
|
||
reject(new Error('导出失败'));
|
||
return;
|
||
}
|
||
const textN = layers.value.filter(l => l.type === 'text').length;
|
||
const paintN = layers.value.filter(l => l.type === 'paint').length;
|
||
resolve({ blob: b, detail: `${layers.value.length} 图层(文字 ${textN} · 画笔 ${paintN})`, w: docW.value, h: docH.value });
|
||
}, mime, 0.94);
|
||
});
|
||
}
|
||
defineExpose({ exportDoc });
|
||
|
||
// ---------- 初始化 ----------
|
||
async function init(): Promise<void> {
|
||
if (!props.file) {
|
||
return;
|
||
}
|
||
const url = URL.createObjectURL(props.file);
|
||
const img = new Image();
|
||
await new Promise<void>((resolve, reject) => {
|
||
img.onload = () => resolve();
|
||
img.onerror = () => reject(new Error('图片加载失败'));
|
||
img.src = url;
|
||
}).finally(() => URL.revokeObjectURL(url));
|
||
docW.value = img.naturalWidth;
|
||
docH.value = img.naturalHeight;
|
||
baseCanvas = document.createElement('canvas');
|
||
baseCanvas.width = docW.value;
|
||
baseCanvas.height = docH.value;
|
||
baseCanvas.getContext('2d')!.drawImage(img, 0, 0);
|
||
const il: ImageLayer = { id: uid(), type: 'image', name: '背景图层', visible: true, opacity: 100 };
|
||
layers.value = [il];
|
||
activeLayerId.value = il.id;
|
||
ocrHits.value = [];
|
||
selHitId.value = null;
|
||
hitStyle.value = null;
|
||
selection.value = null;
|
||
dragRect.value = null;
|
||
ensureComp();
|
||
composite();
|
||
await nextTick();
|
||
fit();
|
||
hist.value = [];
|
||
hIdx.value = -1;
|
||
commit('打开图片');
|
||
// 上传前模板墙选中的模板:图片就绪后立即套入画布(实时可见)
|
||
if (props.autoTpl && !autoTplConsumed) {
|
||
autoTplConsumed = true; // 只套一次
|
||
applyTpl(props.autoTpl);
|
||
emit('applied');
|
||
}
|
||
}
|
||
|
||
watch(() => props.file, () => {
|
||
init().catch(e => emit('error', e?.message ?? '初始化失败'));
|
||
});
|
||
|
||
onMounted(() => {
|
||
init().catch(e => emit('error', e?.message ?? '初始化失败'));
|
||
resizeObs = new ResizeObserver(() => scheduleRender());
|
||
if (viewEl.value) {
|
||
resizeObs.observe(viewEl.value);
|
||
}
|
||
window.addEventListener('keydown', onKeyDown);
|
||
window.addEventListener('keyup', onKeyUp);
|
||
});
|
||
onBeforeUnmount(() => {
|
||
resizeObs?.disconnect();
|
||
window.removeEventListener('keydown', onKeyDown);
|
||
window.removeEventListener('keyup', onKeyUp);
|
||
});
|
||
</script>
|
||
|
||
<template>
|
||
<div class="psx">
|
||
<!-- 工具栏 + 选项栏 -->
|
||
<div class="psx-top">
|
||
<div class="psx-tools">
|
||
<button
|
||
v-for="t in TOOLS"
|
||
:key="t.key"
|
||
class="psx-tool"
|
||
:class="{ on: tool === t.key }"
|
||
:title="t.title"
|
||
@click="tool = t.key"
|
||
>
|
||
{{ t.icon }}
|
||
</button>
|
||
<span class="psx-sep" />
|
||
<button class="psx-tool" title="撤销 (Ctrl+Z)" :disabled="hIdx <= 0" @click="undo()">↶</button>
|
||
<button class="psx-tool" title="重做 (Ctrl+Y)" :disabled="hIdx >= hist.length - 1" @click="redo()">↷</button>
|
||
</div>
|
||
<div class="psx-opts">
|
||
<template v-if="preview">
|
||
<span class="psx-live">👁 实时预览已生成</span>
|
||
<button class="psx-btn primary" title="把预览结果写入图层(Ctrl+Z 可撤销)" @click="applyPreview()">
|
||
✓ 应用消除
|
||
</button>
|
||
<button class="psx-btn" @click="cancelPreview()">✕ 取消预览</button>
|
||
<span class="psx-tip">效果已在画布上显示,满意就应用</span>
|
||
</template>
|
||
<template v-if="tool === 'brush' || tool === 'eraser'">
|
||
<span class="psx-lb">{{ tool === 'eraser' && activeLayer?.type !== 'paint' ? '笔头' : '大小' }}</span>
|
||
<input v-model.number="brushSize" type="range" min="1" max="200" class="psx-range">
|
||
<span class="psx-num">{{ brushSize }}px</span>
|
||
<template v-if="tool === 'brush'">
|
||
<span class="psx-lb">颜色</span>
|
||
<input v-model="brushColor" type="color" class="psx-color" title="画笔颜色">
|
||
</template>
|
||
<span v-if="tool === 'eraser' && activeLayer?.type !== 'paint'" class="psx-tip">涂文字上,松手立即消除</span>
|
||
</template>
|
||
<template v-else-if="tool === 'text'">
|
||
<input v-model="newText" class="psx-textin" placeholder="文字内容,点击画布放置">
|
||
<span class="psx-lb">字号</span>
|
||
<input v-model.number="fontSize" type="number" min="6" max="600" class="psx-numin">
|
||
<input v-model="fontColor" type="color" class="psx-color" title="文字颜色">
|
||
<label class="psx-check"><input v-model="fontBold" type="checkbox"> 加粗</label>
|
||
</template>
|
||
<template v-else-if="tool === 'fill'">
|
||
<span class="psx-lb">容差</span>
|
||
<input v-model.number="tolerance" type="range" min="0" max="90" class="psx-range">
|
||
<span class="psx-num">{{ tolerance }}</span>
|
||
<span class="psx-lb">颜色</span>
|
||
<input v-model="brushColor" type="color" class="psx-color" title="填充颜色">
|
||
</template>
|
||
<template v-else-if="tool === 'marquee' && selection">
|
||
<span class="psx-num">选区 {{ selection.w }}×{{ selection.h }}</span>
|
||
<button v-if="!preview" class="psx-btn primary" title="识别选区内的文字/水印并从背景重建(无痕消除)" @click="inpaintSelection">
|
||
🧹 生成消除预览
|
||
</button>
|
||
<button class="psx-btn" @click="fillSelection">填充选区</button>
|
||
<button class="psx-btn" @click="clearSelection">清除选区</button>
|
||
<button class="psx-btn" @click="selection = null; cancelPreview()">取消选区</button>
|
||
</template>
|
||
<template v-else-if="tool === 'crop'">
|
||
<button v-if="dragRect" class="psx-btn primary" @click="applyCrop">✂ 应用裁剪 {{ dragRect.w }}×{{ dragRect.h }}</button>
|
||
<span v-else class="psx-tip">拖拽框选裁剪区域</span>
|
||
</template>
|
||
<button class="psx-btn" :disabled="ocrBusy" @click="runOcr()">
|
||
{{ ocrBusy ? '识别中…' : '🔍 识别图中文字' }}
|
||
</button>
|
||
<template v-if="selHit">
|
||
<span v-if="hitStyle" class="psx-hitbadge" title="自动检测的原文字样式,新字将按此渲染">
|
||
检出 {{ hitStyle.colorName }}{{ hitStyle.bold ? '·粗' : '' }}·{{ hitStyle.size }}px{{ hitStyle.angle ? `·${hitStyle.angle}°` : '' }}
|
||
</span>
|
||
<input
|
||
v-model="hitText"
|
||
class="psx-textin"
|
||
:placeholder="`原「${selHit.text}」→ 输入新文字(实时预览)`"
|
||
@input="scheduleRender()"
|
||
@keyup.enter="applyHitReplace()"
|
||
>
|
||
<button class="psx-btn primary" title="无缝擦除原字并按同样式重绘新字(一步撤销)" @click="applyHitReplace()">
|
||
✨ 无痕改字
|
||
</button>
|
||
<button v-if="!preview" class="psx-btn" title="识别文字笔画并从周边背景扩散重建,无痕删除" @click="applyHitErase()">
|
||
🧹 只消除
|
||
</button>
|
||
<span v-else class="psx-tip">已实时预览 → 点上方「✓ 应用消除」</span>
|
||
</template>
|
||
<span class="psx-flex" />
|
||
<button class="psx-btn" title="适应窗口 (0)" @click="fit()">适应</button>
|
||
<button class="psx-btn" title="100% (1)" @click="setZoom(1)">100%</button>
|
||
<span class="psx-zoom">{{ Math.round(zoom * 100) }}%</span>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 主区 -->
|
||
<div class="psx-main">
|
||
<div
|
||
ref="viewEl"
|
||
class="psx-view"
|
||
@pointerdown="onDown"
|
||
@pointermove="onMove"
|
||
@pointerup="onUp"
|
||
@pointercancel="onUp"
|
||
@pointerleave="onUp"
|
||
@wheel.prevent="onWheel"
|
||
@contextmenu.prevent
|
||
>
|
||
<canvas ref="viewCanvas" :style="{ cursor: cursorCss }" />
|
||
</div>
|
||
<div class="psx-side">
|
||
<div v-if="docW" class="psx-sec psx-tpl-sec">
|
||
<div class="psx-sec-t">
|
||
✨ 文字模板
|
||
<span class="psx-tip">{{ TEXT_TPLS.length }} 套 · 点击即插入</span>
|
||
</div>
|
||
<div class="psx-tpl-cats">
|
||
<button
|
||
v-for="c in ['全部', ...TPL_CATS]"
|
||
:key="c"
|
||
class="psx-tpl-cat"
|
||
:class="{ on: tplCat === c }"
|
||
@click="tplCat = c"
|
||
>{{ c }}</button>
|
||
</div>
|
||
<div class="psx-tpl-grid">
|
||
<button
|
||
v-for="t in sideTpls"
|
||
:key="t.id"
|
||
class="psx-tpl"
|
||
:title="`[${t.cat}] ${t.name}:${t.parts.join(' / ')} — ${activeLayer?.type === 'text' ? '应用样式到当前文字' : '插入整组文案'}`"
|
||
@click="applyTpl(t)"
|
||
>
|
||
<span class="psx-tpl-txt" :style="tplStyle(t)">{{ t.parts[0] }}</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div class="psx-sec">
|
||
<div class="psx-sec-t">
|
||
图层
|
||
<button class="psx-mini" title="新建画笔图层" @click="addPaintLayer()">+</button>
|
||
</div>
|
||
<div class="psx-layers">
|
||
<div
|
||
v-for="l in [...layers].reverse()"
|
||
:key="l.id"
|
||
class="psx-layer"
|
||
:class="{ on: l.id === activeLayerId }"
|
||
@click="activeLayerId = l.id; scheduleRender()"
|
||
>
|
||
<a
|
||
href="javascript:;"
|
||
class="psx-eye"
|
||
:title="l.visible ? '隐藏' : '显示'"
|
||
@click.stop="l.visible = !l.visible; onLayerPropChange()"
|
||
>{{ l.visible ? '👁' : '🚫' }}</a>
|
||
<span class="psx-badge">{{ l.type === 'text' ? 'T' : l.type === 'fill' ? '■' : l.type === 'paint' ? '🖌' : '🖼' }}</span>
|
||
<span class="lname" :title="l.name">{{ l.name }}</span>
|
||
<template v-if="l.type !== 'image'">
|
||
<a href="javascript:;" class="psx-act" title="上移" @click.stop="moveLayer(l.id, 1)">▲</a>
|
||
<a href="javascript:;" class="psx-act" title="下移" @click.stop="moveLayer(l.id, -1)">▼</a>
|
||
<a href="javascript:;" class="psx-act del" title="删除图层" @click.stop="removeLayer(l.id)">✕</a>
|
||
</template>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div v-if="activeLayer && activeLayer.type !== 'image'" class="psx-sec">
|
||
<div class="psx-sec-t">属性</div>
|
||
<div class="psx-prop">
|
||
<span class="psx-lb">不透明度</span>
|
||
<input
|
||
v-model.number="activeLayer.opacity"
|
||
type="range"
|
||
min="5"
|
||
max="100"
|
||
class="psx-range"
|
||
@input="onLayerPropChange()"
|
||
@change="commitProps()"
|
||
>
|
||
<span class="psx-num">{{ activeLayer.opacity }}%</span>
|
||
</div>
|
||
<template v-if="activeLayer.type === 'text'">
|
||
<div class="psx-prop">
|
||
<span class="psx-lb">内容</span>
|
||
<input v-model="activeLayer.text" class="psx-textin" @change="commitProps()">
|
||
</div>
|
||
<div class="psx-prop">
|
||
<span class="psx-lb">字号</span>
|
||
<input v-model.number="activeLayer.size" type="number" min="6" max="600" class="psx-numin" @change="commitProps()">
|
||
<input v-model="activeLayer.color" type="color" class="psx-color" @change="commitProps()">
|
||
<label class="psx-check"><input v-model="activeLayer.bold" type="checkbox" @change="commitProps()"> 加粗</label>
|
||
</div>
|
||
<div class="psx-prop">
|
||
<span class="psx-lb">旋转</span>
|
||
<input
|
||
v-model.number="activeLayer.rot"
|
||
type="range"
|
||
min="-180"
|
||
max="180"
|
||
class="psx-range"
|
||
@input="onLayerPropChange()"
|
||
@change="commitProps()"
|
||
>
|
||
<input v-model.number="activeLayer.rot" type="number" min="-180" max="180" class="psx-numin rot90" @change="commitProps()">
|
||
<span class="psx-lb">°</span>
|
||
<button class="psx-mini" title="画布上拖蓝色圆点可自由旋转,按 Shift 吸附 15°" @click="activeLayer.rot = 0; commitProps()">回正</button>
|
||
</div>
|
||
</template>
|
||
<template v-else-if="activeLayer.type === 'fill'">
|
||
<div class="psx-prop">
|
||
<span class="psx-lb">底色</span>
|
||
<input v-model="activeLayer.color" type="color" class="psx-color" @change="commitProps()">
|
||
</div>
|
||
</template>
|
||
</div>
|
||
<div class="psx-sec psx-hist-sec">
|
||
<div class="psx-sec-t">历史记录</div>
|
||
<div class="psx-hist">
|
||
<div
|
||
v-for="(h, i) in [...hist].map((x, i) => ({ ...x, i })).reverse()"
|
||
:key="h.i"
|
||
class="psx-hitem"
|
||
:class="{ on: h.i === hIdx, dim: h.i > hIdx }"
|
||
@click="jumpHist(h.i)"
|
||
>
|
||
{{ h.label }}
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 状态栏 -->
|
||
<div class="psx-status">
|
||
<span>{{ docW }}×{{ docH }}px · 图层 {{ layers.length }} · Ctrl+Z 撤销</span>
|
||
<span class="psx-flex" />
|
||
<span class="psx-shint">{{ statusHint }}</span>
|
||
<span class="psx-tip">编辑完成后点下方「执行」导出成品</span>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
|
||
<style scoped lang="less">
|
||
.psx {
|
||
display: flex;
|
||
flex-direction: column;
|
||
width: 100%;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
background: var(--bg-color);
|
||
min-height: 560px;
|
||
user-select: none;
|
||
|
||
&-top {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 6px;
|
||
padding: 8px 10px;
|
||
border-bottom: 1px solid var(--border-color);
|
||
background: var(--bg-color);
|
||
}
|
||
|
||
&-tools {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
&-tool {
|
||
width: 34px;
|
||
height: 30px;
|
||
border: 1px solid transparent;
|
||
border-radius: 6px;
|
||
background: transparent;
|
||
cursor: pointer;
|
||
font-size: 15px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
color: var(--text-color);
|
||
|
||
&:hover {
|
||
background: var(--button-color-hover, rgba(128, 128, 128, 0.15));
|
||
}
|
||
&.on {
|
||
background: #2563eb;
|
||
color: #fff;
|
||
}
|
||
&:disabled {
|
||
opacity: 0.35;
|
||
cursor: default;
|
||
}
|
||
}
|
||
|
||
&-sep {
|
||
width: 1px;
|
||
height: 20px;
|
||
background: var(--border-color);
|
||
margin: 0 6px;
|
||
}
|
||
|
||
&-opts {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
font-size: 12px;
|
||
color: var(--text-color);
|
||
}
|
||
|
||
&-lb {
|
||
opacity: 0.75;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
&-range {
|
||
width: 110px;
|
||
accent-color: #2563eb;
|
||
}
|
||
|
||
&-num {
|
||
min-width: 44px;
|
||
text-align: center;
|
||
font-variant-numeric: tabular-nums;
|
||
}
|
||
|
||
&-numin {
|
||
width: 64px;
|
||
padding: 3px 6px;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 5px;
|
||
background: var(--bg-color);
|
||
color: var(--text-color);
|
||
}
|
||
|
||
&-color {
|
||
width: 30px;
|
||
height: 26px;
|
||
padding: 0;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 5px;
|
||
background: none;
|
||
cursor: pointer;
|
||
}
|
||
|
||
&-hitbadge {
|
||
background: rgba(37, 99, 235, 0.12);
|
||
border: 1px solid rgba(37, 99, 235, 0.4);
|
||
color: #2563eb;
|
||
border-radius: 6px;
|
||
font-size: 11px;
|
||
line-height: 1;
|
||
padding: 5px 8px;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
&-textin {
|
||
flex: 0 1 220px;
|
||
min-width: 120px;
|
||
padding: 4px 8px;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 5px;
|
||
background: var(--bg-color);
|
||
color: var(--text-color);
|
||
}
|
||
|
||
&-check {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
white-space: nowrap;
|
||
cursor: pointer;
|
||
}
|
||
|
||
&-btn {
|
||
padding: 4px 10px;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 6px;
|
||
background: var(--bg-color);
|
||
color: var(--text-color);
|
||
cursor: pointer;
|
||
white-space: nowrap;
|
||
|
||
&:hover {
|
||
border-color: #2563eb;
|
||
}
|
||
&.primary {
|
||
background: #2563eb;
|
||
border-color: #2563eb;
|
||
color: #fff;
|
||
}
|
||
&:disabled {
|
||
opacity: 0.5;
|
||
cursor: default;
|
||
}
|
||
}
|
||
|
||
&-tpl-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(4, 1fr);
|
||
gap: 6px;
|
||
}
|
||
|
||
&-tpl-cats {
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 4px;
|
||
margin-bottom: 7px;
|
||
}
|
||
|
||
&-tpl-cat {
|
||
border: 1px solid rgba(128, 128, 128, 0.32);
|
||
background: transparent;
|
||
color: inherit;
|
||
border-radius: 999px;
|
||
font-size: 10.5px;
|
||
line-height: 1;
|
||
padding: 4px 8px;
|
||
cursor: pointer;
|
||
opacity: 0.75;
|
||
transition: all 0.12s;
|
||
|
||
&:hover {
|
||
opacity: 1;
|
||
border-color: #2563eb;
|
||
}
|
||
|
||
&.on {
|
||
background: #2563eb;
|
||
border-color: #2563eb;
|
||
color: #fff;
|
||
opacity: 1;
|
||
}
|
||
}
|
||
|
||
&-tpl-txt {
|
||
font-size: 11.5px;
|
||
line-height: 1.12;
|
||
text-align: center;
|
||
display: -webkit-box;
|
||
-webkit-line-clamp: 2;
|
||
-webkit-box-orient: vertical;
|
||
overflow: hidden;
|
||
word-break: break-all;
|
||
}
|
||
|
||
&-tpl {
|
||
height: 46px;
|
||
border: 1px solid rgba(128, 128, 128, 0.3);
|
||
border-radius: 7px;
|
||
background: rgba(128, 128, 128, 0.07);
|
||
cursor: pointer;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
overflow: hidden;
|
||
padding: 0 3px;
|
||
transition: border-color 0.12s, transform 0.12s;
|
||
|
||
&:hover {
|
||
border-color: #2563eb;
|
||
transform: translateY(-1px);
|
||
}
|
||
&.on {
|
||
border-color: #2563eb;
|
||
background: rgba(37, 99, 235, 0.12);
|
||
}
|
||
}
|
||
|
||
&-rot90 {
|
||
width: 58px;
|
||
}
|
||
|
||
&-live {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
padding: 3px 9px;
|
||
border-radius: 999px;
|
||
background: rgba(37, 99, 235, 0.14);
|
||
color: #2563eb;
|
||
font-weight: 600;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
&-flex {
|
||
flex: 1;
|
||
}
|
||
|
||
&-tip {
|
||
opacity: 0.55;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
&-zoom {
|
||
min-width: 48px;
|
||
text-align: right;
|
||
font-variant-numeric: tabular-nums;
|
||
opacity: 0.8;
|
||
}
|
||
|
||
&-main {
|
||
flex: 1;
|
||
display: flex;
|
||
min-height: 0;
|
||
}
|
||
|
||
&-view {
|
||
flex: 1;
|
||
position: relative;
|
||
min-width: 0;
|
||
background: #3c3f41;
|
||
overflow: hidden;
|
||
|
||
canvas {
|
||
display: block;
|
||
position: absolute;
|
||
inset: 0;
|
||
touch-action: none;
|
||
}
|
||
}
|
||
|
||
&-side {
|
||
width: 230px;
|
||
border-left: 1px solid var(--border-color);
|
||
display: flex;
|
||
flex-direction: column;
|
||
min-height: 0;
|
||
overflow-y: auto; // 模板库/属性/历史多区块时可滚动到底
|
||
background: var(--bg-color);
|
||
|
||
&::-webkit-scrollbar {
|
||
width: 6px;
|
||
}
|
||
&::-webkit-scrollbar-thumb {
|
||
background: rgba(128, 128, 128, 0.35);
|
||
border-radius: 3px;
|
||
}
|
||
}
|
||
|
||
&-sec {
|
||
padding: 8px 10px;
|
||
border-bottom: 1px solid var(--border-color);
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 6px;
|
||
}
|
||
|
||
&-hist-sec {
|
||
min-height: 0;
|
||
border-bottom: none;
|
||
}
|
||
|
||
&-sec-t {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
font-size: 12px;
|
||
font-weight: 600;
|
||
opacity: 0.85;
|
||
}
|
||
|
||
&-mini {
|
||
width: 22px;
|
||
height: 22px;
|
||
border: 1px solid var(--border-color);
|
||
border-radius: 5px;
|
||
background: transparent;
|
||
color: var(--text-color);
|
||
cursor: pointer;
|
||
|
||
&:hover {
|
||
border-color: #2563eb;
|
||
}
|
||
}
|
||
|
||
&-layers {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 3px;
|
||
max-height: 220px;
|
||
overflow-y: auto;
|
||
}
|
||
|
||
&-layer {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
padding: 4px 6px;
|
||
border: 1px solid transparent;
|
||
border-radius: 6px;
|
||
cursor: pointer;
|
||
font-size: 12px;
|
||
|
||
&:hover {
|
||
background: rgba(128, 128, 128, 0.12);
|
||
}
|
||
&.on {
|
||
border-color: #2563eb;
|
||
background: rgba(37, 99, 235, 0.12);
|
||
}
|
||
|
||
.lname {
|
||
flex: 1;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
}
|
||
|
||
&-eye {
|
||
font-size: 12px;
|
||
text-decoration: none;
|
||
opacity: 0.85;
|
||
}
|
||
|
||
&-badge {
|
||
width: 20px;
|
||
height: 20px;
|
||
border-radius: 4px;
|
||
background: rgba(128, 128, 128, 0.18);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 11px;
|
||
}
|
||
|
||
&-act {
|
||
text-decoration: none;
|
||
font-size: 10px;
|
||
opacity: 0.6;
|
||
padding: 0 2px;
|
||
|
||
&:hover {
|
||
opacity: 1;
|
||
}
|
||
&.del:hover {
|
||
color: #d03050;
|
||
}
|
||
}
|
||
|
||
&-prop {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
&-hist {
|
||
overflow-y: auto;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 2px;
|
||
max-height: 220px;
|
||
}
|
||
|
||
&-hitem {
|
||
padding: 3px 8px;
|
||
border-radius: 5px;
|
||
font-size: 12px;
|
||
cursor: pointer;
|
||
|
||
&:hover {
|
||
background: rgba(128, 128, 128, 0.12);
|
||
}
|
||
&.on {
|
||
background: rgba(37, 99, 235, 0.16);
|
||
color: #2563eb;
|
||
font-weight: 600;
|
||
}
|
||
&.dim {
|
||
opacity: 0.4;
|
||
}
|
||
}
|
||
|
||
&-status {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
padding: 5px 12px;
|
||
border-top: 1px solid var(--border-color);
|
||
font-size: 11.5px;
|
||
opacity: 0.85;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
&-shint {
|
||
color: #2563eb;
|
||
}
|
||
}
|
||
</style>
|