61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
|
|
import { BaseCommand } from './base-command';
|
||
|
|
import { useLayerStore } from '@/store';
|
||
|
|
import { cloneCanvas } from '@/lib/canvas-utils';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Command for drawing operations
|
||
|
|
* Stores the before/after state of the canvas
|
||
|
|
*/
|
||
|
|
export class DrawCommand extends BaseCommand {
|
||
|
|
private layerId: string;
|
||
|
|
private beforeCanvas: HTMLCanvasElement | null = null;
|
||
|
|
private afterCanvas: HTMLCanvasElement | null = null;
|
||
|
|
|
||
|
|
constructor(layerId: string, toolName: string) {
|
||
|
|
super(`Draw with ${toolName}`);
|
||
|
|
this.layerId = layerId;
|
||
|
|
|
||
|
|
// Store before state
|
||
|
|
const layer = useLayerStore.getState().getLayer(layerId);
|
||
|
|
if (layer?.canvas) {
|
||
|
|
this.beforeCanvas = cloneCanvas(layer.canvas);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Call this after drawing is complete to capture the after state
|
||
|
|
*/
|
||
|
|
captureAfterState(): void {
|
||
|
|
const layer = useLayerStore.getState().getLayer(this.layerId);
|
||
|
|
if (layer?.canvas) {
|
||
|
|
this.afterCanvas = cloneCanvas(layer.canvas);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
execute(): void {
|
||
|
|
if (!this.afterCanvas) return;
|
||
|
|
|
||
|
|
const layer = useLayerStore.getState().getLayer(this.layerId);
|
||
|
|
if (!layer?.canvas) return;
|
||
|
|
|
||
|
|
const ctx = layer.canvas.getContext('2d');
|
||
|
|
if (!ctx) return;
|
||
|
|
|
||
|
|
ctx.clearRect(0, 0, layer.canvas.width, layer.canvas.height);
|
||
|
|
ctx.drawImage(this.afterCanvas, 0, 0);
|
||
|
|
}
|
||
|
|
|
||
|
|
undo(): void {
|
||
|
|
if (!this.beforeCanvas) return;
|
||
|
|
|
||
|
|
const layer = useLayerStore.getState().getLayer(this.layerId);
|
||
|
|
if (!layer?.canvas) return;
|
||
|
|
|
||
|
|
const ctx = layer.canvas.getContext('2d');
|
||
|
|
if (!ctx) return;
|
||
|
|
|
||
|
|
ctx.clearRect(0, 0, layer.canvas.width, layer.canvas.height);
|
||
|
|
ctx.drawImage(this.beforeCanvas, 0, 0);
|
||
|
|
}
|
||
|
|
}
|