UNPKG

js-draw

Version:

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

62 lines (61 loc) 2.21 kB
import { Path } from '@js-draw/math'; import { PathCommandType } from '@js-draw/math'; import SelectionBuilder from './SelectionBuilder.mjs'; /** * Creates lasso selections. */ export default class LassoSelectionBuilder extends SelectionBuilder { constructor(startPoint, viewport) { super(); this.viewport = viewport; this.boundaryPoints = []; this.boundaryPoints.push(startPoint); this.lastPoint = startPoint; } onPointerMove(canvasPoint) { const lastBoundaryPoint = this.boundaryPoints[this.boundaryPoints.length - 1]; const minBoundaryDist = this.viewport.getSizeOfPixelOnCanvas() * 8; if (lastBoundaryPoint.distanceTo(canvasPoint) >= minBoundaryDist) { this.boundaryPoints.push(canvasPoint); } this.lastPoint = canvasPoint; } previewPath() { const pathCommands = this.boundaryPoints.map((point) => { return { kind: PathCommandType.LineTo, point }; }); pathCommands.push({ kind: PathCommandType.LineTo, point: this.lastPoint, }); return new Path(this.boundaryPoints[0], pathCommands).asClosed(); } resolveInternal(image) { const path = this.previewPath(); const lines = path.polylineApproximation(); const candidates = image.getComponentsIntersecting(path.bbox); const componentIsInSelection = (component) => { if (path.closedContainsRect(component.getExactBBox())) { return true; } let hasKeyPoint = false; for (const point of component.keyPoints()) { if (path.closedContainsPoint(point)) { hasKeyPoint = true; break; } } if (!hasKeyPoint) { return false; } // Only select if completely contained within the lasso for (const line of lines) { if (component.intersects(line)) { return false; } } return true; }; return candidates.filter(componentIsInSelection); } }