Skip to main content

Angular Konva Cache Tutorial

To use caching with Konva in Angular, you can use the ng2-konva library with the cache method to improve performance.

For full list of properties and methods, see the Konva API Reference.

Cache 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',
  template: `
    <ko-stage [config]="configStage">
      <ko-layer>
        <ko-rect #rect [config]="configRect"></ko-rect>
      </ko-layer>
    </ko-stage>
  `,
  imports: [StageComponent, CoreShapeComponent],
})
export default class App implements AfterViewInit {
  @ViewChild('rect') rect!: any;

  public configStage: StageConfig = {
    width: window.innerWidth,
    height: window.innerHeight,
  };
  public configRect: RectConfig = {
    x: 50,
    y: 50,
    width: 100,
    height: 100,
    fill: 'red',
    shadowBlur: 10,
    shadowColor: 'black',
    shadowOffsetX: 5,
    shadowOffsetY: 5
  };

  ngAfterViewInit() {
    if (this.rect) {
      this.rect.getNode().cache();
    }
  }
}