Skip to main content

Angular Konva Custom Shape Tutorial

To create a custom shape with ng2-konva, use the ko-shape component and provide a sceneFunc drawing function.

Inside sceneFunc, you can use the native canvas context together with Konva helpers such as context.fillStrokeShape(shape) to apply fill, stroke, and shadow styles correctly.

Instructions: The demo draws a custom triangle-like shape with canvas path commands.

For more details, see the Shape API Reference.

Custom Shape Example

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

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

@Component({
selector: 'app-root',
standalone: true,
template: `
<ko-stage [config]="configStage">
<ko-layer>
<ko-shape [config]="configShape"></ko-shape>
</ko-layer>
</ko-stage>
`,
imports: [StageComponent, CoreShapeComponent],
})
export default class App {
public configStage: StageConfig = {
width: window.innerWidth,
height: window.innerHeight,
};
public configShape: ShapeConfig = {
x: 100,
y: 100,
fill: 'red',
stroke: 'black',
strokeWidth: 2,
sceneFunc: (context: any, shape: any) => {
context.beginPath();
context.moveTo(0, 0);
context.lineTo(100, 0);
context.lineTo(50, 100);
context.closePath();
context.fillStrokeShape(shape);
}
};
}