@inweb/markup
Version:
JavaScript 2D markups
143 lines (110 loc) • 3.15 kB
text/typescript
import Konva from "konva";
import { IMarkupEllipse, IMarkupEllipseParams } from "../IMarkupEllipse";
export class KonvaEllipse implements IMarkupEllipse {
private _ref: Konva.Ellipse;
constructor(params: IMarkupEllipseParams, ref = null) {
if (ref) {
this._ref = ref;
return;
}
if (!params) params = {};
if (!params.position) params.position = { x: 0, y: 0 };
if (!params.radius) params.radius = { x: 25, y: 25 };
this._ref = new Konva.Ellipse({
stroke: params.color ?? "#ff0000",
strokeWidth: params.lineWidth ?? 4,
globalCompositeOperation: "source-over",
lineCap: "round",
lineJoin: "round",
x: params.position.x,
y: params.position.y,
radiusX: params.radius.x,
radiusY: params.radius.y,
draggable: true,
strokeScaleEnabled: false,
});
this._ref.on("transform", (e) => {
const attrs = e.target.attrs;
if (attrs.rotation !== this._ref.rotation()) this._ref.rotation(attrs.rotation);
const scaleByX = Math.abs(attrs.scaleX - 1) > 10e-6;
const scaleByY = Math.abs(attrs.scaleY - 1) > 10e-6;
let newRadiusX = this._ref.radiusX();
if (scaleByX) newRadiusX *= attrs.scaleX;
let newRadiusY = this._ref.radiusY();
if (scaleByY) newRadiusY *= attrs.scaleY;
const minRadiusX = 25;
const minRadiusY = 25;
if (newRadiusX < minRadiusX) newRadiusX = minRadiusX;
if (newRadiusY < minRadiusY) newRadiusY = minRadiusY;
if (e.evt.ctrlKey || e.evt.shiftKey) {
if (scaleByX) {
this._ref.radius({ x: newRadiusX, y: newRadiusX });
} else {
this._ref.radius({ x: newRadiusY, y: newRadiusY });
}
} else {
this._ref.radius({ x: newRadiusX, y: newRadiusY });
}
this._ref.scale({ x: 1, y: 1 });
});
this._ref.id(this._ref._id.toString());
}
getPosition(): { x: number; y: number } {
return this._ref.position();
}
setPosition(x: number, y: number): void {
this._ref.setPosition({ x, y });
}
getRadiusX(): number {
return this._ref.radiusX();
}
setRadiusX(r: number): void {
this._ref.radiusX(r);
}
getRadiusY(): number {
return this._ref.radiusY();
}
setRadiusY(r: number): void {
this._ref.radiusY(r);
}
getLineWidth(): number {
return this._ref.strokeWidth();
}
setLineWidth(size: number): void {
this._ref.strokeWidth(size);
}
ref() {
return this._ref;
}
id(): string {
return this._ref.id();
}
enableMouseEditing(value: boolean): void {
this._ref.draggable(value);
}
type(): string {
return "Ellipse";
}
getColor(): string {
return this._ref.stroke() as string;
}
setColor(hex: string): void {
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;
}
}