import Konva from "konva"; import { IMarkupLine, LineType } from "../../IMarkupLine"; import { IMarkupColorable } from "../../IMarkupColorable"; const LineTypeSpecs = new Map([ [LineType.Solid, []], [LineType.Dot, [30, 30, 0.001, 30]], [LineType.Dash, [30, 30]], ]); export class KonvaLine implements IMarkupLine, IMarkupColorable { private _ref: Konva.Line; constructor( params: { points: { x: number; y: number }[]; color: string; type: LineType; width: number; id?: string }, ref = null ) { if (ref) { this._ref = ref; return; } if (!params.points) return; 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.id(this._ref._id.toString()); } ref() { return this._ref; } id(): string { return this._ref.id(); } enableMouseEditing(value: boolean) { this._ref.draggable(value); } type(): string { return "line"; } getColor(): string { return this._ref.stroke(); } 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 = "solid"; switch (typeSpecs) { case LineTypeSpecs.get(LineType.Dot): type = "dot"; break; case LineTypeSpecs.get(LineType.Dash): type = "dash"; break; } return type; } setLineType(type: string) { const lineType = LineType[type]; if (lineType) { const specs = LineTypeSpecs.get(lineType); 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); } }