Angular Konva Cache Tutorial
Caching rasterizes a node into an internal image, which can improve performance and is required for some effects such as filters.
This example accesses the underlying Konva node after render and calls cache() manually.
Instructions: The demo shows a rectangle with shadow styling that is cached after the view initializes.
For more details, see the Node API Reference and cache() documentation.
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',
standalone: true,
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();
}
}
}