Getting started with Angular and Canvas via Konva
How to use canvas with Angular?
ng2-konva
is a JavaScript library for drawing complex canvas graphics using Angular. It provides declarative and reactive bindings to the Konva Framework.
It is an attempt to make Angular work with the HTML5 canvas library. The goal is to have a similar declarative markup as normal Angular and also a similar data-flow model.
All ng2-konva
components correspond to Konva
components of the same name with the prefix 'ko-'. All the parameters available for Konva
objects can be added as config
in the property binding for corresponding ng2-konva
components.
Core shapes are: ko-rect
, ko-circle
, ko-ellipse
, ko-line
, ko-image
, ko-text
, ko-text-path
, ko-star
, ko-label
, ko-path
, ko-regular-polygon
.
Also you can create custom shapes.
To get more info about Konva
you can read Konva Overview.
Quick Start
Angular version 20+ is required.
1. Install via npm
npm install ng2-konva konva --save
2. Import and use ng2-konva
import {
CoreShapeComponent,
StageComponent,
} from 'ng2-konva';
@Component({
// ... other config
template: `
<ko-stage [config]="configStage">
<ko-layer>
<ko-circle [config]="configCircle"></ko-circle>
</ko-layer>
</ko-stage>
`,
imports: [StageComponent, CoreShapeComponent],
})
export default class App {
public configStage: StageConfig = {
width: window.innerWidth,
height: window.innerHeight,
};
public configCircle: CircleConfig = {
x: 100,
y: 100,
radius: 50,
fill: 'red',
};
}
3. Use in your components
Instructions: Try to drag the stars. They will scale up while being dragged and return to normal size when released.
For full list of properties and methods, see the Konva API Reference.