refactor(*): 代码质量 - 优化前后端实现并完善协议与画布验证
This commit is contained in:
1 parent
d74f783912
commit
295374650a
724 files changed
+3045
-3884
No files matched your search
@@ -29,7 +29,7 @@ export type ResolvedCanvasAppearance = {
|
||||
|
||||
export const DEFAULT_CANVAS_BACKGROUND_MODE: CanvasBackgroundMode = "dots";
|
||||
|
||||
const CANVAS_APPEARANCE_DEFAULT_KEY = "infinite-canvas:canvas-appearance-default";
|
||||
const CANVAS_APPEARANCE_DEFAULT_KEY = "yingce:canvas-appearance-default";
|
||||
const HEX_COLOR_PATTERN = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
|
||||
const CUSTOM_GRID_COLOR: Record<CanvasColorTheme, string> = { light: "#000000", dark: "#000000" };
|
||||
const CUSTOM_GRID_OPACITY: Record<CanvasColorTheme, number> = { light: 80, dark: 100 };
|
||||
|
||||
@@ -32,9 +32,9 @@ export type CanvasDrawingRender = CanvasDrawingRenderDraft & {
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
const drawingStore = localforage.createInstance({ name: "infinite-canvas", storeName: "drawing_documents" });
|
||||
const drawingPreviewStore = localforage.createInstance({ name: "infinite-canvas", storeName: "drawing_previews" });
|
||||
const drawingRenderStore = localforage.createInstance({ name: "infinite-canvas", storeName: "drawing_generation_renders" });
|
||||
const drawingStore = localforage.createInstance({ name: "yingce", storeName: "drawing_documents" });
|
||||
const drawingPreviewStore = localforage.createInstance({ name: "yingce", storeName: "drawing_previews" });
|
||||
const drawingRenderStore = localforage.createInstance({ name: "yingce", storeName: "drawing_generation_renders" });
|
||||
const INITIAL_DRAWING_RENDER_MAX_DIMENSION = 2048;
|
||||
const INITIAL_DRAWING_RENDER_PADDING = 24;
|
||||
|
||||
|
||||
@@ -1,78 +1,46 @@
|
||||
import { saveAs } from "file-saver";
|
||||
|
||||
import { createZip } from "@/lib/zip";
|
||||
import { getMediaBlob } from "@/services/file-storage";
|
||||
import { getImageBlob } from "@/services/image-storage";
|
||||
import type { CanvasExportAsset, CanvasExportFile } from "@/types/canvas-export";
|
||||
import type { CanvasProject } from "@/stores/canvas/use-canvas-store";
|
||||
import { MediaPackage, downloadName, packageSegment, referencedStorageKeys } from "@/lib/media-package";
|
||||
import { loadCanvasDrawing, loadCanvasDrawingPreview, loadCanvasDrawingRender } from "@/lib/canvas/canvas-drawing-storage";
|
||||
import type { CanvasDrawingExport } from "@/types/canvas-export";
|
||||
import type { CanvasDrawingExport, CanvasExportFile, CanvasProjectExportItem } from "@/types/canvas-export";
|
||||
import type { CanvasProject } from "@/stores/canvas/use-canvas-store";
|
||||
|
||||
export async function exportCanvasProjects(projects: CanvasProject[], fileName = "画布", options: { includeLocalDrawings?: boolean } = {}) {
|
||||
const zipFiles: { name: string; data: BlobPart }[] = [];
|
||||
const exportedProjects = await Promise.all(
|
||||
projects.map(async (project) => {
|
||||
const files: CanvasExportAsset[] = [];
|
||||
await Promise.all(
|
||||
collectStorageKeys(project).map(async (storageKey) => {
|
||||
const blob = storageKey.startsWith("image:") ? await getImageBlob(storageKey) : await getMediaBlob(storageKey);
|
||||
if (!blob) return;
|
||||
const path = `projects/${project.id}/files/${safeFileName(storageKey)}.${fileExtension(blob.type, storageKey)}`;
|
||||
files.push({ storageKey, path, mimeType: blob.type || "application/octet-stream", bytes: blob.size });
|
||||
zipFiles.push({ name: path, data: blob });
|
||||
}),
|
||||
);
|
||||
const drawingDocuments = (await Promise.all(project.nodes.filter((node) => options.includeLocalDrawings !== false && node.type === "drawing" && node.metadata?.drawingId).map(async (node): Promise<CanvasDrawingExport | null> => {
|
||||
const drawingId = node.metadata?.drawingId;
|
||||
if (!drawingId) return null;
|
||||
const [saved, preview, render] = await Promise.all([
|
||||
loadCanvasDrawing(project.id, drawingId),
|
||||
loadCanvasDrawingPreview(project.id, drawingId),
|
||||
loadCanvasDrawingRender(project.id, drawingId),
|
||||
]);
|
||||
if (!saved) return null;
|
||||
const previewPath = preview ? `projects/${project.id}/drawings/${safeFileName(drawingId)}.png` : undefined;
|
||||
if (preview && previewPath) zipFiles.push({ name: previewPath, data: preview });
|
||||
const generationRenderPath = render ? `projects/${project.id}/drawings/${safeFileName(drawingId)}.generation.png` : undefined;
|
||||
if (render && generationRenderPath) zipFiles.push({ name: generationRenderPath, data: render.blob });
|
||||
return {
|
||||
drawingId,
|
||||
...saved,
|
||||
previewPath,
|
||||
generationRender: render && generationRenderPath
|
||||
? { path: generationRenderPath, pageId: render.pageId, width: render.width, height: render.height, mimeType: render.mimeType, background: render.background }
|
||||
: undefined,
|
||||
} satisfies CanvasDrawingExport;
|
||||
}))).filter((item): item is CanvasDrawingExport => item !== null);
|
||||
drawingDocuments.forEach((document) => zipFiles.push({ name: `projects/${project.id}/drawings/${safeFileName(document.drawingId)}.json`, data: JSON.stringify(document) }));
|
||||
return { project, files, drawingDocuments };
|
||||
}),
|
||||
);
|
||||
|
||||
const data: CanvasExportFile = { app: "infinite-canvas", version: 4, exportedAt: new Date().toISOString(), projects: exportedProjects };
|
||||
const zip = await createZip([{ name: "projects.json", data: JSON.stringify(data, null, 2) }, ...zipFiles]);
|
||||
saveAs(zip, `${safeFileName(fileName)}.zip`);
|
||||
async function addDrawing(archive: MediaPackage, project: CanvasProject, drawingId: string, directory: string): Promise<CanvasDrawingExport | null> {
|
||||
const document = await loadCanvasDrawing(project.id, drawingId);
|
||||
if (!document) return null;
|
||||
const stem = `${directory}/drawings/${packageSegment(drawingId)}`;
|
||||
const [preview, generation] = await Promise.all([loadCanvasDrawingPreview(project.id, drawingId), loadCanvasDrawingRender(project.id, drawingId)]);
|
||||
const saved: CanvasDrawingExport = { ...document, drawingId };
|
||||
if (preview) { saved.previewPath = `${stem}.png`; archive.put(saved.previewPath, preview); }
|
||||
if (generation) {
|
||||
const { pageId, width, height, mimeType, background } = generation;
|
||||
saved.generationRender = { path: `${stem}.generation.png`, pageId, width, height, mimeType, background };
|
||||
archive.put(saved.generationRender.path, generation.blob);
|
||||
}
|
||||
archive.put(`${stem}.json`, JSON.stringify(saved));
|
||||
return saved;
|
||||
}
|
||||
|
||||
function collectStorageKeys(value: unknown, keys = new Set<string>()) {
|
||||
if (!value || typeof value !== "object") return [...keys];
|
||||
if ("storageKey" in value && typeof value.storageKey === "string" && value.storageKey.includes(":")) keys.add(value.storageKey);
|
||||
Object.values(value).forEach((item) => (Array.isArray(item) ? item.forEach((child) => collectStorageKeys(child, keys)) : collectStorageKeys(item, keys)));
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
function safeFileName(value: string) {
|
||||
return value.replace(/[\\/:*?"<>|]/g, "_");
|
||||
}
|
||||
|
||||
function fileExtension(mimeType: string, storageKey: string) {
|
||||
if (mimeType.includes("png")) return "png";
|
||||
if (mimeType.includes("jpeg")) return "jpg";
|
||||
if (mimeType.includes("webp")) return "webp";
|
||||
if (mimeType.includes("gif")) return "gif";
|
||||
if (mimeType.includes("mp4")) return "mp4";
|
||||
if (mimeType.includes("webm")) return "webm";
|
||||
if (mimeType.includes("gltf-binary")) return "glb";
|
||||
if (mimeType.includes("gltf+json")) return "gltf";
|
||||
return storageKey.startsWith("image:") ? "png" : "bin";
|
||||
export async function exportCanvasProjects(projects: CanvasProject[], fileName = "画布", options: { includeLocalDrawings?: boolean } = {}): Promise<void> {
|
||||
const archive = new MediaPackage();
|
||||
const items: CanvasProjectExportItem[] = [];
|
||||
// Snapshot once so edits during asynchronous blob reads cannot change the manifest midway.
|
||||
const snapshot = structuredClone(projects);
|
||||
const projectIds = new Set<string>();
|
||||
for (const project of snapshot) {
|
||||
if (projectIds.has(project.id)) throw new Error("不能重复导出同一个画布项目");
|
||||
projectIds.add(project.id);
|
||||
const directory = `projects/${packageSegment(project.id)}`;
|
||||
const files = await archive.collect(referencedStorageKeys(project), `${directory}/files`);
|
||||
const drawingDocuments: CanvasDrawingExport[] = [];
|
||||
if (options.includeLocalDrawings !== false) {
|
||||
const ids = new Set(project.nodes.flatMap((node) => node.type === "drawing" && node.metadata?.drawingId ? [node.metadata.drawingId] : []));
|
||||
for (const drawingId of ids) {
|
||||
const document = await addDrawing(archive, project, drawingId, directory);
|
||||
if (document) drawingDocuments.push(document);
|
||||
}
|
||||
}
|
||||
items.push({ project, files, drawingDocuments });
|
||||
}
|
||||
const manifest: CanvasExportFile = { app: "yingce", version: 4, exportedAt: new Date().toISOString(), projects: items };
|
||||
saveAs(await archive.finish("projects.json", manifest), `${downloadName(fileName)}.zip`);
|
||||
}
|
||||
@@ -1,182 +1,54 @@
|
||||
export type ImageCropRect = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
import { loadRasterImage } from "@/lib/image-raster";
|
||||
import { planImageTiles, resolveCropPixels, resolveUpscaleSize, type ImageCropRect, type ImageSplitParams, type ImageSplitPiece, type ImageUpscaleAlgorithm, type ImageUpscaleParams, type PixelSize } from "./image-operation-plan";
|
||||
|
||||
export { MAX_UPSCALE_LONG_EDGE, resolveUpscaleSize } from "./image-operation-plan";
|
||||
export type { ImageCropRect, ImageSplitParams, ImageSplitPiece, ImageUpscaleAlgorithm, ImageUpscaleParams } from "./image-operation-plan";
|
||||
|
||||
type RasterCommand = {
|
||||
region: ImageCropRect;
|
||||
output: PixelSize;
|
||||
sampling: ImageUpscaleAlgorithm;
|
||||
};
|
||||
|
||||
export type ImageAngleTransform = {
|
||||
horizontalAngle: number;
|
||||
pitchAngle: number;
|
||||
cameraDistance: number;
|
||||
wideAngle: boolean;
|
||||
};
|
||||
|
||||
export type ImageUpscaleAlgorithm = "nearest" | "bilinear" | "high";
|
||||
|
||||
export const MAX_UPSCALE_LONG_EDGE = 4096;
|
||||
|
||||
export type ImageUpscaleParams = {
|
||||
targetLongEdge: number;
|
||||
algorithm: ImageUpscaleAlgorithm;
|
||||
};
|
||||
|
||||
export type ImageSplitParams = {
|
||||
rows: number;
|
||||
columns: number;
|
||||
};
|
||||
|
||||
export type ImageSplitPiece = {
|
||||
row: number;
|
||||
column: number;
|
||||
dataUrl: string;
|
||||
};
|
||||
|
||||
export async function cropDataUrl(dataUrl: string, crop?: ImageCropRect) {
|
||||
const image = await loadImage(dataUrl);
|
||||
if (crop) {
|
||||
return drawCrop(image, Math.floor(crop.x * image.width), Math.floor(crop.y * image.height), Math.ceil(crop.width * image.width), Math.ceil(crop.height * image.height));
|
||||
}
|
||||
const size = Math.min(image.width, image.height);
|
||||
const sx = Math.max(0, Math.floor((image.width - size) / 2));
|
||||
const sy = Math.max(0, Math.floor((image.height - size) / 2));
|
||||
return drawCrop(image, sx, sy, size, size);
|
||||
/** One raster pass shared by crop, grid extraction and resize. Failures never return the original as success. */
|
||||
function renderPng(source: HTMLImageElement, command: RasterCommand): string {
|
||||
const output = document.createElement("canvas");
|
||||
Object.assign(output, command.output);
|
||||
const painter = output.getContext("2d");
|
||||
if (painter === null) throw new Error("浏览器无法创建图片处理画布");
|
||||
const { region, sampling } = command;
|
||||
painter.imageSmoothingEnabled = sampling !== "nearest";
|
||||
painter.imageSmoothingQuality = sampling === "high" ? "high" : "low";
|
||||
painter.drawImage(source, region.x, region.y, region.width, region.height, 0, 0, output.width, output.height);
|
||||
const result = output.toDataURL("image/png");
|
||||
if (!result.startsWith("data:image/png")) throw new Error("图片导出失败");
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function splitDataUrl(dataUrl: string, params: ImageSplitParams): Promise<ImageSplitPiece[]> {
|
||||
const image = await loadImage(dataUrl);
|
||||
const rows = Math.max(1, Math.floor(params.rows));
|
||||
const columns = Math.max(1, Math.floor(params.columns));
|
||||
const pieces: ImageSplitPiece[] = [];
|
||||
const dimensions = (image: HTMLImageElement): PixelSize => ({ width: image.naturalWidth, height: image.naturalHeight });
|
||||
|
||||
for (let row = 0; row < rows; row += 1) {
|
||||
const sy = Math.floor((row * image.height) / rows);
|
||||
const sh = Math.floor(((row + 1) * image.height) / rows) - sy;
|
||||
for (let column = 0; column < columns; column += 1) {
|
||||
const sx = Math.floor((column * image.width) / columns);
|
||||
const sw = Math.floor(((column + 1) * image.width) / columns) - sx;
|
||||
pieces.push({ row, column, dataUrl: drawCrop(image, sx, sy, sw, sh) });
|
||||
}
|
||||
}
|
||||
|
||||
return pieces;
|
||||
export async function cropDataUrl(source: string, selection?: ImageCropRect): Promise<string> {
|
||||
const picture = await loadRasterImage(source);
|
||||
const region = resolveCropPixels(dimensions(picture), selection);
|
||||
return renderPng(picture, { region, output: { width: region.width, height: region.height }, sampling: "nearest" });
|
||||
}
|
||||
|
||||
export async function transformAngleDataUrl(dataUrl: string, params: ImageAngleTransform) {
|
||||
const image = await loadImage(dataUrl);
|
||||
const canvas = document.createElement("canvas");
|
||||
const padding = Math.round(Math.max(image.width, image.height) * 0.18);
|
||||
canvas.width = image.width + padding * 2;
|
||||
canvas.height = image.height + padding * 2;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return dataUrl;
|
||||
context.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
const horizontal = params.horizontalAngle / 60;
|
||||
const pitch = params.pitchAngle / 45;
|
||||
const distanceScale = 1.12 - params.cameraDistance * 0.035;
|
||||
const wideScale = params.wideAngle ? 0.88 : 1;
|
||||
const scale = Math.max(0.64, Math.min(1.1, distanceScale * wideScale));
|
||||
const width = image.width * scale * (1 - Math.abs(horizontal) * 0.28);
|
||||
const height = image.height * scale * (1 - Math.abs(pitch) * 0.18);
|
||||
const cx = canvas.width / 2;
|
||||
const cy = canvas.height / 2;
|
||||
const skewX = horizontal * image.width * 0.18;
|
||||
const skewY = pitch * image.height * 0.12;
|
||||
const x = cx - width / 2 + horizontal * padding * 0.5;
|
||||
const y = cy - height / 2 + pitch * padding * 0.45;
|
||||
|
||||
context.save();
|
||||
context.setTransform(1, pitch * 0.08, horizontal * -0.1, 1, 0, 0);
|
||||
context.drawImage(image, x + skewX, y + skewY, width, height);
|
||||
context.restore();
|
||||
|
||||
if (params.wideAngle) {
|
||||
const gradient = context.createRadialGradient(cx, cy, Math.min(canvas.width, canvas.height) * 0.2, cx, cy, Math.max(canvas.width, canvas.height) * 0.62);
|
||||
gradient.addColorStop(0, "rgba(255,255,255,0)");
|
||||
gradient.addColorStop(1, "rgba(0,0,0,0.18)");
|
||||
context.fillStyle = gradient;
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
|
||||
return canvas.toDataURL("image/png");
|
||||
export async function splitDataUrl(source: string, grid: ImageSplitParams): Promise<ImageSplitPiece[]> {
|
||||
const picture = await loadRasterImage(source);
|
||||
return planImageTiles(dimensions(picture), grid).map((region) => ({
|
||||
row: region.row,
|
||||
column: region.column,
|
||||
dataUrl: renderPng(picture, { region, output: { width: region.width, height: region.height }, sampling: "nearest" }),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function upscaleDataUrl(dataUrl: string, params: ImageUpscaleParams) {
|
||||
const image = await loadImage(dataUrl);
|
||||
const { width, height } = resolveUpscaleSize(image.width, image.height, params.targetLongEdge);
|
||||
return params.algorithm === "high" ? drawStepUpscale(image, width, height) : drawResize(image, image.width, image.height, width, height, params.algorithm);
|
||||
}
|
||||
|
||||
export function resolveUpscaleSize(width: number, height: number, targetLongEdge: number) {
|
||||
const longEdge = Math.max(1, width, height);
|
||||
const target = Math.min(MAX_UPSCALE_LONG_EDGE, Math.max(1, Math.round(targetLongEdge)));
|
||||
const scale = target / longEdge;
|
||||
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||
}
|
||||
|
||||
function drawCrop(image: HTMLImageElement, sx: number, sy: number, sw: number, sh: number) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, sw);
|
||||
canvas.height = Math.max(1, sh);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return image.src;
|
||||
context.drawImage(image, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
function drawStepUpscale(image: HTMLImageElement, width: number, height: number) {
|
||||
let source: CanvasImageSource = image;
|
||||
let sourceWidth = image.width;
|
||||
let sourceHeight = image.height;
|
||||
|
||||
while (sourceWidth * 2 < width && sourceHeight * 2 < height) {
|
||||
const nextWidth = sourceWidth * 2;
|
||||
const nextHeight = sourceHeight * 2;
|
||||
const next = drawResizeCanvas(source, sourceWidth, sourceHeight, nextWidth, nextHeight, "high");
|
||||
source = next;
|
||||
sourceWidth = nextWidth;
|
||||
sourceHeight = nextHeight;
|
||||
}
|
||||
|
||||
return drawResize(source, sourceWidth, sourceHeight, width, height, "high");
|
||||
}
|
||||
|
||||
function drawResize(source: CanvasImageSource, sourceWidth: number, sourceHeight: number, width: number, height: number, algorithm: ImageUpscaleAlgorithm) {
|
||||
return drawResizeCanvas(source, sourceWidth, sourceHeight, width, height, algorithm).toDataURL("image/png");
|
||||
}
|
||||
|
||||
function drawResizeCanvas(source: CanvasImageSource, sourceWidth: number, sourceHeight: number, width: number, height: number, algorithm: ImageUpscaleAlgorithm) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return canvas;
|
||||
context.imageSmoothingEnabled = algorithm !== "nearest";
|
||||
context.imageSmoothingQuality = algorithm === "bilinear" ? "medium" : "high";
|
||||
context.drawImage(source, 0, 0, sourceWidth, sourceHeight, 0, 0, width, height);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function loadImage(dataUrl: string) {
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const image = new Image();
|
||||
// 只有跨源 HTTP(S) 地址才需要声明匿名跨域;同源的 /api 资源不能
|
||||
// 强制走 CORS,否则缺少 ACAO 响应头时反而会加载失败。
|
||||
if (isCrossOriginHttpUrl(dataUrl)) image.crossOrigin = "anonymous";
|
||||
image.onload = () => resolve(image);
|
||||
// 缺少 onerror 时加载失败会让 Promise 永久挂起,调用方 await 后表现为「点击无反应」。
|
||||
image.onerror = () => reject(new Error("图片加载失败,无法处理该图片"));
|
||||
image.src = dataUrl;
|
||||
export async function upscaleDataUrl(source: string, options: ImageUpscaleParams): Promise<string> {
|
||||
if (!["nearest", "bilinear", "high"].includes(options.algorithm)) throw new RangeError("不支持的图片插值方式");
|
||||
const picture = await loadRasterImage(source);
|
||||
const size = dimensions(picture);
|
||||
return renderPng(picture, {
|
||||
region: { ...size, x: 0, y: 0 },
|
||||
output: resolveUpscaleSize(size.width, size.height, options.targetLongEdge),
|
||||
sampling: options.algorithm,
|
||||
});
|
||||
}
|
||||
|
||||
function isCrossOriginHttpUrl(value: string) {
|
||||
if (typeof window === "undefined") return false;
|
||||
try {
|
||||
const url = new URL(value, window.location.href);
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && url.origin !== window.location.origin;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { ImageCropRect } from "./image-operation-plan";
|
||||
export type CropGrip = readonly [-1 | 0 | 1, -1 | 0 | 1];
|
||||
const limit = (n: number, a: number, b: number) => Math.max(a, Math.min(b, n));
|
||||
const minimum = 0.06;
|
||||
|
||||
export function translateSelection(box: ImageCropRect, dx: number, dy: number): ImageCropRect {
|
||||
return { width: box.width, height: box.height, x: limit(box.x + dx, 0, 1 - box.width), y: limit(box.y + dy, 0, 1 - box.height) };
|
||||
}
|
||||
|
||||
export function resizeSelection(box: ImageCropRect, grip: CropGrip, dx: number, dy: number, fixedAspect: boolean): ImageCropRect {
|
||||
const [horizontal, vertical] = grip;
|
||||
if (!horizontal && !vertical) return box;
|
||||
if (!fixedAspect) {
|
||||
const minWidth = Math.min(minimum, box.width);
|
||||
const minHeight = Math.min(minimum, box.height);
|
||||
const left = horizontal < 0 ? limit(box.x + dx, 0, box.x + box.width - minWidth) : box.x;
|
||||
const right = horizontal > 0 ? limit(box.x + box.width + dx, box.x + minWidth, 1) : box.x + box.width;
|
||||
const top = vertical < 0 ? limit(box.y + dy, 0, box.y + box.height - minHeight) : box.y;
|
||||
const bottom = vertical > 0 ? limit(box.y + box.height + dy, box.y + minHeight, 1) : box.y + box.height;
|
||||
return { x: left, y: top, width: right - left, height: bottom - top };
|
||||
}
|
||||
// Project the gesture onto the original rectangle's scale vector around its opposite anchor.
|
||||
const fx = (1 - horizontal) / 2;
|
||||
const fy = (1 - vertical) / 2;
|
||||
const ax = box.x + box.width * fx;
|
||||
const ay = box.y + box.height * fy;
|
||||
const vx = horizontal * box.width;
|
||||
const vy = vertical * box.height;
|
||||
const proposed = 1 + (dx * vx + dy * vy) / (vx * vx + vy * vy);
|
||||
const capacity = (anchor: number, fraction: number) => Math.min(fraction ? anchor / fraction : Infinity, fraction < 1 ? (1 - anchor) / (1 - fraction) : Infinity);
|
||||
const ceiling = Math.min(capacity(ax, fx) / box.width, capacity(ay, fy) / box.height);
|
||||
const floor = Math.min(ceiling, Math.max(minimum / box.width, minimum / box.height));
|
||||
const factor = limit(proposed, floor, ceiling);
|
||||
const width = box.width * factor;
|
||||
const height = box.height * factor;
|
||||
return { x: ax - width * fx, y: ay - height * fy, width, height };
|
||||
}
|
||||
|
||||
export function selectAspect(box: ImageCropRect, normalizedRatio: number): ImageCropRect {
|
||||
if (!Number.isFinite(normalizedRatio) || normalizedRatio <= 0) throw new RangeError("裁剪比例无效");
|
||||
const height = Math.min(1, 1 / normalizedRatio, Math.sqrt((box.width * box.height) / normalizedRatio));
|
||||
const width = height * normalizedRatio;
|
||||
return { width, height, x: limit(box.x + (box.width - width) / 2, 0, 1 - width), y: limit(box.y + (box.height - height) / 2, 0, 1 - height) };
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
export type MaskPoint = readonly [number, number];
|
||||
export type MaskStroke = { diameter: number; erase: boolean; points: MaskPoint[] };
|
||||
|
||||
/** A stroke document is the source of truth; previews and exported masks are separate renders. */
|
||||
export function paintMaskStrokes(canvas: HTMLCanvasElement, strokes: readonly MaskStroke[], color: string): CanvasRenderingContext2D {
|
||||
const brush = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (!brush) throw new Error("无法创建遮罩画布");
|
||||
brush.clearRect(0, 0, canvas.width, canvas.height);
|
||||
brush.lineCap = "round";
|
||||
brush.lineJoin = "round";
|
||||
brush.fillStyle = brush.strokeStyle = color;
|
||||
for (const stroke of strokes) {
|
||||
const first = stroke.points[0];
|
||||
if (!first) continue;
|
||||
brush.globalCompositeOperation = stroke.erase ? "destination-out" : "source-over";
|
||||
brush.lineWidth = stroke.diameter;
|
||||
const path = new Path2D();
|
||||
if (stroke.points.length === 1) {
|
||||
path.arc(first[0], first[1], stroke.diameter / 2, 0, Math.PI * 2);
|
||||
brush.fill(path);
|
||||
} else {
|
||||
path.moveTo(first[0], first[1]);
|
||||
for (const [x, y] of stroke.points.slice(1)) path.lineTo(x, y);
|
||||
brush.stroke(path);
|
||||
}
|
||||
}
|
||||
brush.globalCompositeOperation = "source-over";
|
||||
return brush;
|
||||
}
|
||||
|
||||
export function invertSelectionAlpha(selection: Uint8ClampedArray): Uint8ClampedArray {
|
||||
if (selection.length % 4 !== 0) throw new RangeError("遮罩像素数据无效");
|
||||
let selected = false;
|
||||
const result = new Uint8ClampedArray(selection.length).fill(255);
|
||||
for (let pixel = 0; pixel < selection.length / 4; pixel++) {
|
||||
if (selection[pixel * 4 + 3] === 0) continue;
|
||||
selected = true;
|
||||
result[pixel * 4 + 3] = 0;
|
||||
}
|
||||
if (!selected) throw new Error("请先涂抹需要修改的区域");
|
||||
return result;
|
||||
}
|
||||
|
||||
export function exportEditMask(width: number, height: number, strokes: readonly MaskStroke[]): string {
|
||||
const surface = document.createElement("canvas");
|
||||
Object.assign(surface, { width, height });
|
||||
const brush = paintMaskStrokes(surface, strokes, "black");
|
||||
const pixels = brush.getImageData(0, 0, width, height);
|
||||
pixels.data.set(invertSelectionAlpha(pixels.data));
|
||||
brush.putImageData(pixels, 0, 0);
|
||||
const png = surface.toDataURL("image/png");
|
||||
if (!png.startsWith("data:image/png")) throw new Error("遮罩导出失败");
|
||||
return png;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
export interface PixelSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Normalized image coordinates, independent of the preview's CSS dimensions. */
|
||||
export interface ImageCropRect extends PixelSize {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export type ImageUpscaleAlgorithm = "nearest" | "bilinear" | "high";
|
||||
export interface ImageUpscaleParams {
|
||||
targetLongEdge: number;
|
||||
algorithm: ImageUpscaleAlgorithm;
|
||||
}
|
||||
export interface ImageSplitParams {
|
||||
rows: number;
|
||||
columns: number;
|
||||
}
|
||||
export interface ImageSplitPiece {
|
||||
row: number;
|
||||
column: number;
|
||||
dataUrl: string;
|
||||
}
|
||||
export const MAX_UPSCALE_LONG_EDGE = 4096;
|
||||
export const MAX_IMAGE_GRID = 12;
|
||||
|
||||
export function assertPixelSize(size: PixelSize): void {
|
||||
if (![size.width, size.height].every((n) => Number.isSafeInteger(n) && n > 0)) {
|
||||
throw new RangeError("图片尺寸必须是正整数");
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveUpscaleSize(width: number, height: number, requested: number): PixelSize {
|
||||
assertPixelSize({ width, height });
|
||||
if (!Number.isFinite(requested) || requested <= 0) throw new RangeError("目标尺寸无效");
|
||||
const edge = Math.max(1, Math.min(MAX_UPSCALE_LONG_EDGE, Math.round(requested)));
|
||||
return width >= height
|
||||
? { width: edge, height: Math.max(1, Math.round((height / width) * edge)) }
|
||||
: { width: Math.max(1, Math.round((width / height) * edge)), height: edge };
|
||||
}
|
||||
|
||||
export function resolveCropPixels(size: PixelSize, selection?: ImageCropRect): ImageCropRect {
|
||||
assertPixelSize(size);
|
||||
if (selection === undefined) {
|
||||
const side = Math.min(size.width, size.height);
|
||||
return { width: side, height: side, x: Math.floor((size.width - side) / 2), y: Math.floor((size.height - side) / 2) };
|
||||
}
|
||||
const { x, y, width, height } = selection;
|
||||
if (![x, y, width, height].every(Number.isFinite) || width <= 0 || height <= 0) throw new RangeError("裁剪区域无效");
|
||||
const left = Math.max(0, Math.floor(x * size.width));
|
||||
const top = Math.max(0, Math.floor(y * size.height));
|
||||
const right = Math.min(size.width, Math.ceil((x + width) * size.width));
|
||||
const bottom = Math.min(size.height, Math.ceil((y + height) * size.height));
|
||||
if (left >= right || top >= bottom) throw new RangeError("裁剪区域超出图片边界");
|
||||
return { x: left, y: top, width: right - left, height: bottom - top };
|
||||
}
|
||||
|
||||
/** Shared integer boundaries ensure every source pixel belongs to exactly one tile. */
|
||||
export function planImageTiles(size: PixelSize, grid: ImageSplitParams): Array<ImageCropRect & { row: number; column: number }> {
|
||||
assertPixelSize(size);
|
||||
if (![grid.rows, grid.columns].every((n) => Number.isInteger(n) && n >= 1 && n <= MAX_IMAGE_GRID)) throw new RangeError("切分行列数必须在 1 到 12 之间");
|
||||
if (grid.columns > size.width || grid.rows > size.height) throw new RangeError("切分数量不能超过图片像素尺寸");
|
||||
const edges = (length: number, count: number) => Array.from({ length: count + 1 }, (_, i) => Math.floor((length * i) / count));
|
||||
const horizontal = edges(size.width, grid.columns);
|
||||
const vertical = edges(size.height, grid.rows);
|
||||
return Array.from({ length: grid.rows * grid.columns }, (_, index) => {
|
||||
const column = index % grid.columns;
|
||||
const row = Math.floor(index / grid.columns);
|
||||
return { column, row, x: horizontal[column], y: vertical[row], width: horizontal[column + 1] - horizontal[column], height: vertical[row + 1] - vertical[row] };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Position } from "@/types/canvas";
|
||||
|
||||
export type NodeResizeCorner = "top-left" | "top-right" | "bottom-left" | "bottom-right";
|
||||
export type NodeResizeSnapshot = {
|
||||
position: Position;
|
||||
width: number;
|
||||
height: number;
|
||||
minimumWidth: number;
|
||||
minimumHeight: number;
|
||||
ratio?: number;
|
||||
corner: NodeResizeCorner;
|
||||
};
|
||||
|
||||
/** Solve size first, then retain the diagonally opposite world-space anchor. */
|
||||
export function solveNodeResize(start: NodeResizeSnapshot, delta: Position): { width: number; height: number; position: Position } {
|
||||
const sx = start.corner.endsWith("left") ? -1 : 1;
|
||||
const sy = start.corner.startsWith("top") ? -1 : 1;
|
||||
let width = Math.max(start.minimumWidth, start.width + sx * delta.x);
|
||||
let height = Math.max(start.minimumHeight, start.height + sy * delta.y);
|
||||
const ratio = start.ratio;
|
||||
if (ratio !== undefined && Number.isFinite(ratio) && ratio > 0) {
|
||||
// Preserve the existing dominant-pointer-axis gesture, including horizontal ties.
|
||||
const requestedHeight = Math.abs(delta.x) >= Math.abs(delta.y) ? width / ratio : height;
|
||||
height = Math.max(start.minimumHeight, start.minimumWidth / ratio, requestedHeight);
|
||||
width = height * ratio;
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
position: {
|
||||
x: start.position.x + (sx < 0 ? start.width - width : 0),
|
||||
y: start.position.y + (sy < 0 ? start.height - height : 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user