js-draw
Version:
Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.
68 lines (67 loc) • 2.49 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const math_1 = require("@js-draw/math");
const math_2 = require("@js-draw/math");
const SelectionBuilder_1 = __importDefault(require("./SelectionBuilder"));
/**
* Creates lasso selections.
*/
class LassoSelectionBuilder extends SelectionBuilder_1.default {
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: math_2.PathCommandType.LineTo, point };
});
pathCommands.push({
kind: math_2.PathCommandType.LineTo,
point: this.lastPoint,
});
return new math_1.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);
}
}
exports.default = LassoSelectionBuilder;