Files
it-tools-pro/src/tools/image-tools/PsEditor.vue
T
personal82555 72e06b24fe feat(image-tools): 智能消除——无痕删除图中文字/水印(inpainting)
- inpaintRect(): 笔画像素检测(与环带中位色差异>42)+ 1px 抗锯齿膨胀
  + Gauss-Seidel 交替方向扩散重建(自适应迭代次数),渐变/纹理背景自然补全
- OCR 路径:点框「🧹 消除文字」(替代原纯色覆盖的只擦除)
- 选框路径:「🧹 消除选区内容」一键消除,无需 OCR;选项栏显示选区尺寸
- 结果写入独立「智能消除」画笔层:非破坏性/可撤销/可再编辑
- 修复 mask 边界:检测覆盖选区全部像素(原跳过边缘 2px,边缘字符残留)
- 修复视口偏移:尺寸变化时按中心补偿 pan(布局稳定后图片偏移致坐标错位)
- 实测:渐变底双语测试图,OCR 路径蓝字 5136→0 且红字保留;选框路径
  红字 6517→0 且蓝字保留;Python 独立复现对照验证算法一致性
2026-10-21 20:46:58 +08:00

1916 lines
55 KiB
Vue
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.
<script setup lang="ts">
// PS 风格图片编辑器:工具栏 / 选项栏 / 画布(缩放平移)/ 图层面板 / 历史记录
// 图层类型:image(底图) / paint(画笔涂改层) / text(文字层) / fill(色块擦除层)
import { useStorage } from '@vueuse/core';
import { licenseHeaders } from '@/tools/license/license';
const props = defineProps<{ file: File }>();
const emit = defineEmits<{ (e: 'error', msg: string): void }>();
// ---------- 文档状态 ----------
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;
}
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', 36);
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 (tool.value === 'brush' || tool.value === 'eraser') {
return `大小 ${brushSize.value}px,按 [ ] 调整`;
}
if (tool.value === 'move') {
return '拖动文字/色块;选中画笔层后可整体移动';
}
if (tool.value === 'marquee') {
return '拖拽框选,松手后可「消除选区内容」(无痕去文字/水印)或填充/清除';
}
if (tool.value === 'text') {
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> {
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 {
ls.push(raw as Layer);
}
}
layers.value = ls;
activeLayerId.value = st.active ?? ls[ls.length - 1]?.id ?? '';
ensureComp();
composite();
scheduleRender();
}
function commit(label: string): void {
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') {
ctx.font = `${l.bold ? 'bold ' : ''}${l.size}px "Microsoft YaHei","PingFang SC","Noto Sans CJK SC","Source Han Sans SC",sans-serif`;
ctx.fillStyle = l.color;
ctx.textBaseline = 'top';
ctx.fillText(l.text, l.x, l.y);
}
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 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);
}
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);
ctx.strokeRect(al.x - 3 / zoom.value, al.y - 3 / zoom.value, m.w + 6 / zoom.value, m.h + 6 / zoom.value);
}
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();
// 屏幕空间叠加层
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 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): 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 };
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 };
layers.value.push(tl);
activeLayerId.value = tl.id;
commit('添加文字');
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 ok = inpaintRect(s);
if (ok) {
selection.value = null;
commit('智能消除选区');
composite();
scheduleRender();
}
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);
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';
}
}
function applyHitReplace(): void {
const hit = selHit.value;
if (!hit || hit.used) {
return;
}
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);
const content = hitText.value.trim() || hit.text;
const tl: TextLayer = { 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 };
layers.value.push(tl);
activeLayerId.value = tl.id;
hit.used = true;
selHitId.value = null;
hitText.value = '';
commit('OCR 替换文字');
composite();
scheduleRender();
}
function applyHitErase(): void {
const hit = selHit.value;
if (!hit || hit.used) {
return;
}
// 智能消除:识别笔画像素,从周边背景扩散重建(inpainting)
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);
const ok = inpaintRect(rect);
if (!ok) {
return;
}
hit.used = true;
selHitId.value = null;
commit('OCR 消除文字');
composite();
scheduleRender();
}
// ---------- 智能消除(inpainting) ----------
// 1) 取矩形区域(含外扩边距)像素;2) 与周边背景色差异大的判为文字笔画;
// 3) 笔画像素由四周已知像素迭代扩散重建(Gauss-Seidel),背景连续纹理/渐变都能自然补上;
// 4) 只把重建像素写入一个新的「智能消除」画笔层,非破坏性、可撤销、可再编辑。
function inpaintRect(rect: { x: number; y: number; w: number; h: number }): boolean {
if (!compCanvas || rect.w < 2 || rect.h < 2) {
return false;
}
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;
// 1) 背景色:区域外圈 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 false;
}
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);
// 2) 笔画掩码:与背景色差异大的像素(全区域检测,含边缘字符)
const mask = new Uint8Array(rw * rh);
let unknown = 0;
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 false; // 没检出文字,无需处理
}
// 掩码向外扩 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++;
}
}
}
// 3) 扩散重建:未知像素反复取四邻均值(迭代次数随区域尺寸自适应)
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 iters = Math.min(500, Math.max(rw, rh) * 2);
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;
}
}
}
}
// 4) 写入独立画笔层(只含重建区域,其余透明)
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);
const pl = createPaintLayer('智能消除');
pl.canvas.getContext('2d')!.drawImage(tmp, rx, ry);
return true;
}
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 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') {
const m = textMetrics(l);
if (dx >= l.x - 4 && dx <= l.x + m.w + 4 && dy >= l.y - 4 && dy <= l.y + m.h + 4) {
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 = '';
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 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;
}
return;
}
if (tool.value === 'brush' || tool.value === 'eraser') {
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 (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 (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 (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;
}
// 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;
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;
}
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;
selection.value = null;
dragRect.value = null;
ensureComp();
composite();
await nextTick();
fit();
hist.value = [];
hIdx.value = -1;
commit('打开图片');
}
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="tool === 'brush' || tool === 'eraser'">
<span class="psx-lb">大小</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>
</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 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; scheduleRender()">取消选区</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">
<input v-model="hitText" class="psx-textin" :placeholder="selHit.text" @keyup.enter="applyHitReplace()">
<button class="psx-btn primary" @click="applyHitReplace()">✓ 替换</button>
<button class="psx-btn" title="识别文字笔画并从周边背景扩散重建,无痕删除" @click="applyHitErase()">
🧹 消除文字
</button>
</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 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>
</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;
}
&-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;
}
}
&-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;
background: var(--bg-color);
}
&-sec {
padding: 8px 10px;
border-bottom: 1px solid var(--border-color);
display: flex;
flex-direction: column;
gap: 6px;
}
&-hist-sec {
flex: 1;
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 {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 2px;
min-height: 60px;
}
&-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>