excalidraw/src/element/newElement.ts

75 lines
1.5 KiB
TypeScript
Raw Normal View History

import { randomSeed } from "roughjs/bin/math";
import nanoid from "nanoid";
import { Drawable } from "roughjs/bin/core";
import { Point } from "roughjs/bin/geometry";
import { ExcalidrawElement, ExcalidrawTextElement } from "../element/types";
import { measureText } from "../utils";
export function newElement(
type: string,
x: number,
y: number,
strokeColor: string,
backgroundColor: string,
fillStyle: string,
strokeWidth: number,
roughness: number,
opacity: number,
width = 0,
2020-01-24 12:04:54 +02:00
height = 0,
) {
const element = {
id: nanoid(),
type,
x,
y,
width,
height,
strokeColor,
backgroundColor,
fillStyle,
strokeWidth,
roughness,
opacity,
isSelected: false,
seed: randomSeed(),
2020-01-24 12:04:54 +02:00
shape: null as Drawable | Drawable[] | null,
points: [] as Point[],
};
return element;
}
2020-01-08 19:54:42 +01:00
export function newTextElement(
element: ExcalidrawElement,
text: string,
2020-01-24 12:04:54 +02:00
font: string,
) {
const metrics = measureText(text, font);
const textElement: ExcalidrawTextElement = {
...element,
type: "text",
text: text,
font: font,
// Center the text
x: element.x - metrics.width / 2,
y: element.y - metrics.height / 2,
width: metrics.width,
height: metrics.height,
2020-01-24 12:04:54 +02:00
baseline: metrics.baseline,
};
return textElement;
}
2020-01-08 19:54:42 +01:00
export function duplicateElement(element: ReturnType<typeof newElement>) {
const copy = {
...element,
points: JSON.parse(JSON.stringify(element.points)),
};
delete copy.shape;
2020-01-08 19:54:42 +01:00
copy.id = nanoid();
copy.seed = randomSeed();
return copy;
}