跳到主要内容

Angular Konva 撤销/重做教程

将 Canvas state 存储在普通数据对象中,而不是在每次渲染时从 Canvas 读回值,可使撤销和重做达到最佳效果。

本示例将矩形位置存储在小型历史记录栈中。单击撤销或重做时,示例会恢复之前的快照。

操作说明:拖动矩形以创建历史记录条目,然后单击撤销和重做以浏览已保存的 state。

有关更多详细信息,请参阅 Rect API 参考

撤销/重做示例

import { Component } from '@angular/core';
import { StageConfig } from 'konva/lib/Stage';
import { RectConfig } from 'konva/lib/shapes/Rect';

import {
  CoreShapeComponent,
  StageComponent,
} from 'ng2-konva';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div>
      <button (click)="undo()" [disabled]="!canUndo()">Undo</button>
      <button (click)="redo()" [disabled]="!canRedo()">Redo</button>
      <ko-stage [config]="configStage">
        <ko-layer>
          <ko-rect 
            [config]="configRect"
            (dragend)="handleDragEnd($event.event)"
          ></ko-rect>
        </ko-layer>
      </ko-stage>
    </div>
  `,
  imports: [StageComponent, CoreShapeComponent],
})
export default class App {
  private history: RectConfig[] = [];
  private currentIndex: number = -1;

  public configStage: StageConfig = {
    width: window.innerWidth,
    height: window.innerHeight,
  };
  public configRect: RectConfig = {
    x: 100,
    y: 100,
    width: 100,
    height: 100,
    fill: 'red',
    draggable: true
  };

  constructor() {
    this.saveState();
  }

  private saveState(): void {
    // Remove any states after current index
    this.history = this.history.slice(0, this.currentIndex + 1);
    
    // Add current state
    this.history.push({ ...this.configRect });
    this.currentIndex++;
  }

  public handleDragEnd(event: any): void {
    this.configRect = {
      ...this.configRect,
      x: event.target.x(),
      y: event.target.y()
    };
    this.saveState();
  }

  public undo(): void {
    if (this.canUndo()) {
      this.currentIndex--;
      this.configRect = { ...this.history[this.currentIndex] };
    }
  }

  public redo(): void {
    if (this.canRedo()) {
      this.currentIndex++;
      this.configRect = { ...this.history[this.currentIndex] };
    }
  }

  public canUndo(): boolean {
    return this.currentIndex > 0;
  }

  public canRedo(): boolean {
    return this.currentIndex < this.history.length - 1;
  }
}

手动构建历史记录的局限

上述历史记录每一步只记录一个值。生产级编辑器必须记录 成组操作,使多选拖动可以作为一个步骤撤销,还必须记录 变换,以及操作完成后才加载完的图像。该状态机 通常比绘图代码更庞大,因此请围绕文档操作而不是原始节点状态来设计历史记录。