@inweb/markup
Version:
JavaScript 2D markups
138 lines (110 loc) • 2.81 kB
text/typescript
import Konva from "konva";
import { IMarkupLine, IMarkupLineParams, MarkupLineType } from "../IMarkupLine";
const LineTypeSpecs = new Map<string, number[]>([
["solid", []],
["dot", [30, 30, 0.001, 30]],
["dash", [30, 30]],
]);
export class KonvaLine implements IMarkupLine {
private _ref: Konva.Line;
constructor(params: IMarkupLineParams, ref = null) {
if (ref) {
this._ref = ref;
return;
}
if (!params) params = {};
if (!params.points)
params.points = [
{ x: 0, y: 0 },
{ x: 100, y: 100 },
];
const konvaPoints = [];
params.points.forEach((point) => konvaPoints.push(point.x, point.y));
this._ref = new Konva.Line({
stroke: params.color ?? "#ff0000",
strokeWidth: params.width ?? 4,
globalCompositeOperation: "source-over",
lineCap: "round",
lineJoin: "round",
points: konvaPoints,
draggable: true,
strokeScaleEnabled: false,
dash: LineTypeSpecs.get(params.type) || [],
});
this._ref.on("transform", (e) => {
const attrs = e.target.attrs;
if (attrs.rotation !== this._ref.rotation()) this._ref.rotation(attrs.rotation);
});
this._ref.id(this._ref._id.toString());
}
ref() {
return this._ref;
}
id(): string {
return this._ref.id();
}
enableMouseEditing(value: boolean): void {
this._ref.draggable(value);
}
type(): string {
return "Line";
}
getColor(): string {
return this._ref.stroke() as string;
}
setColor(hex: string) {
this._ref.stroke(hex);
}
getRotation(): number {
return this._ref.rotation();
}
setRotation(degrees: number): void {
this._ref.rotation(degrees);
}
getZIndex(): number {
return this._ref.zIndex();
}
setZIndex(zIndex: number): void {
this._ref.zIndex(zIndex);
}
delete() {
this._ref.destroy();
this._ref = null;
}
getPoints(): number[] {
return this._ref.points();
}
setLineWidth(size: number) {
this._ref.strokeWidth(size);
}
getLineWidth(): number {
return this._ref.strokeWidth();
}
getLineType(): string {
const typeSpecs = this._ref.dash() || [];
let type: MarkupLineType;
switch (typeSpecs) {
case LineTypeSpecs.get("dot"):
type = "dot";
break;
case LineTypeSpecs.get("dash"):
type = "dash";
break;
default:
type = "solid";
break;
}
return type;
}
setLineType(type: string) {
const specs = LineTypeSpecs.get(type);
if (specs) this._ref.dash(specs);
}
addPoints(points: [{ x: number; y: number }]) {
let newPoints = this._ref.points();
points.forEach((point) => {
newPoints = newPoints.concat([point.x, point.y]);
});
this._ref.points(newPoints);
}
}