UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

65 lines (64 loc) 2.31 kB
import { Path, PathCommandType } from '@js-draw/math'; import { pathToRenderable } from '../../rendering/RenderablePathSpec.mjs'; import Stroke from '../Stroke.mjs'; import makeSnapToGridAutocorrect from './autocorrect/makeSnapToGridAutocorrect.mjs'; /** * Creates a stroke builder that generates filled lines. * * Example: * [[include:doc-pages/inline-examples/changing-pen-types.md]] */ export const makeLineBuilder = makeSnapToGridAutocorrect((initialPoint, viewport) => { return new LineBuilder(initialPoint, viewport); }); export default class LineBuilder { constructor(startPoint, viewport) { this.startPoint = startPoint; this.viewport = viewport; this.endPoint = startPoint; } getBBox() { const preview = this.buildPreview(); return preview.getBBox(); } buildPreview() { const startPoint = this.startPoint.pos; const endPoint = this.endPoint.pos; const toEnd = endPoint.minus(startPoint).normalized(); const startSize = this.startPoint.width / 2; const endSize = this.endPoint.width / 2; const lineNormal = toEnd.orthog(); const scaledStartNormal = lineNormal.times(startSize); const scaledEndNormal = lineNormal.times(endSize); const strokeStartPoint = startPoint.minus(scaledStartNormal); const path = new Path(strokeStartPoint, [ { kind: PathCommandType.LineTo, point: startPoint.plus(scaledStartNormal), }, { kind: PathCommandType.LineTo, point: endPoint.plus(scaledEndNormal), }, { kind: PathCommandType.LineTo, point: endPoint.minus(scaledEndNormal), }, { kind: PathCommandType.LineTo, point: startPoint.minus(scaledStartNormal), }, ]).mapPoints((point) => this.viewport.roundPoint(point)); const preview = new Stroke([pathToRenderable(path, { fill: this.startPoint.color })]); return preview; } build() { return this.buildPreview(); } preview(renderer) { this.buildPreview().render(renderer); } addPoint(point) { this.endPoint = point; } }