Skip to main content

Angular Konva Transformer Tutorial

The Transformer tool is attached to nodes imperatively. In Angular, that means creating a ko-transformer and connecting it to the selected shape after the view is ready.

Instructions: Click the rectangle to select it, drag it to move it, and click on the empty stage to clear the selection.

For more details, see the Transformer API Reference.

Transformer Example

import { Component, ViewChild, AfterViewInit } 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: `
    <ko-stage [config]="configStage" (click)="handleStageClick($event.event)">
      <ko-layer>
        <ko-rect
          #rect
          [config]="configRect"
          (click)="handleShapeClick()"
        ></ko-rect>
        <ko-transformer #transformer></ko-transformer>
      </ko-layer>
    </ko-stage>
  `,
  imports: [StageComponent, CoreShapeComponent],
})
export default class App implements AfterViewInit {
  @ViewChild('rect') rect!: any;
  @ViewChild('transformer') transformer!: any;

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

  ngAfterViewInit() {
    this.transformer.getNode().nodes([this.rect.getNode()]);
  }

  public handleStageClick(event: any): void {
    if (event?.target === event.target.getStage()) {
      this.transformer.getNode().nodes([]);
    }
  }

  public handleShapeClick(): void {
    this.transformer.getNode().nodes([this.rect.getNode()]);
  }
}