UNPKG

@inweb/markup

Version:
133 lines (100 loc) 2.81 kB
import Konva from "konva"; import { IMarkupText, IMarkupTextParams } from "../IMarkupText"; export class KonvaText implements IMarkupText { private _ref: Konva.Text; private readonly TEXT_FONT_FAMILY = "Calibri"; constructor(params: IMarkupTextParams, ref = null) { if (ref) { this._ref = ref; return; } if (!params) params = {}; if (!params.position) params.position = { x: 0, y: 0 }; if (!params.text) params.text = "default"; this._ref = new Konva.Text({ x: params.position.x, y: params.position.y, text: params.text, fontSize: params.fontSize ?? 34, fontFamily: this.TEXT_FONT_FAMILY, fill: params.color ?? "#ff0000", align: "left", draggable: true, rotation: params.rotation ?? 0, }); this._ref.width(this._ref.getTextWidth()); 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 newWidth = this._ref.width(); if (scaleByX) newWidth *= attrs.scaleX; let newHeight = this._ref.height(); if (scaleByY) newHeight *= attrs.scaleY; const minWidth = 50; if (newWidth < minWidth) newWidth = minWidth; if (newHeight < Math.round(this.getFontSize())) newHeight = Math.round(this.getFontSize()); if (scaleByX) { this._ref.width(newWidth); } if (scaleByY) { this._ref.height(newHeight); } this._ref.scale({ x: 1, y: 1 }); }); 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 "Text"; } getColor(): string { return this._ref.fill() as string; } setColor(hex: string): void { this._ref.fill(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; } getText(): string { return this._ref.text(); } setText(text: string): void { this._ref.text(text); } getPosition(): { x: number; y: number } { return this._ref.getPosition(); } setPosition(x: number, y: number): void { this._ref.setPosition({ x, y }); } getFontSize(): number { return this._ref.fontSize(); } setFontSize(size: number): void { this._ref.fontSize(size); } }