anki/ts/image-occlusion/shapes/text.ts
Abdo 9e147c6335
Add text tool to image occlusion (#2705)
* Add text tool to IO

* Remove unnecessary parentheses

* Fix text objects always grouped

* Remove log

* Fix text objects hidden on back side

* Implement text scaling

* Add inverse text outline

* Warn about IO notes with only text objects

This will result in a different error message than the case where no
objects are added at all though, and the user can bypass the warning.
Maybe this is better to avoid discarding the user's work if they have
spent some time adding text.

* Add isValidType

* Use matches!

* Lock aspect ratio of text objects

* Reword misleading comment

The confusion probably comes from the Fabric docs, which apparently need updating: http://fabricjs.com/docs/fabric.Canvas.html#uniformScaling

* Do not count text objects when calculating current index

* Make text objects respond to size changes

* Fix uniform scaling not working when editing

* Use Arial font

* Escape colons and unify parsing

* Handle scale factor when restricting shape to view

* Use 'cloned'

* Add text background

* Tweak drawShape's params
2023-10-12 13:40:11 +10:00

66 lines
1.9 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { fabric } from "fabric";
import { SHAPE_MASK_COLOR, TEXT_FONT_FAMILY, TEXT_PADDING } from "../tools/lib";
import type { ConstructorParams, Size } from "../types";
import type { ShapeDataForCloze } from "./base";
import { Shape } from "./base";
import { floatToDisplay } from "./floats";
import { xFromNormalized, xToNormalized, yFromNormalized, yToNormalized } from "./position";
export class Text extends Shape {
text: string;
scaleX: number;
scaleY: number;
constructor({
text = "",
scaleX = 1,
scaleY = 1,
...rest
}: ConstructorParams<Text> = {}) {
super(rest);
this.text = text;
this.scaleX = scaleX;
this.scaleY = scaleY;
}
toDataForCloze(): TextDataForCloze {
return {
...super.toDataForCloze(),
text: this.text,
// scaleX and scaleY are guaranteed to be equal since we lock the aspect ratio
scale: floatToDisplay(this.scaleX),
};
}
toFabric(size: Size): fabric.IText {
this.makeAbsolute(size);
return new fabric.IText(this.text, {
...this,
fontFamily: TEXT_FONT_FAMILY,
backgroundColor: SHAPE_MASK_COLOR,
padding: TEXT_PADDING,
});
}
makeNormal(size: Size): void {
super.makeNormal(size);
this.scaleX = xToNormalized(size, this.scaleX);
this.scaleY = yToNormalized(size, this.scaleY);
}
makeAbsolute(size: Size): void {
super.makeAbsolute(size);
this.scaleX = xFromNormalized(size, this.scaleX);
this.scaleY = yFromNormalized(size, this.scaleY);
}
}
interface TextDataForCloze extends ShapeDataForCloze {
text: string;
scale: string;
}