face-api/src/draw/DrawBox.ts

69 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-12-23 17:26:55 +01:00
/* eslint-disable max-classes-per-file */
2020-12-19 17:46:41 +01:00
import { Box, IBoundingBox, IRect } from '../classes/index';
2020-08-18 13:54:53 +02:00
import { getContext2dOrThrow } from '../dom/getContext2dOrThrow';
2021-03-19 23:46:36 +01:00
import { AnchorPosition, DrawTextField, DrawTextFieldOptions, IDrawTextFieldOptions } from './DrawTextField';
2020-08-18 13:54:53 +02:00
export interface IDrawBoxOptions {
boxColor?: string
lineWidth?: number
drawLabelOptions?: IDrawTextFieldOptions
label?: string
}
export class DrawBoxOptions {
public boxColor: string
2020-12-23 17:26:55 +01:00
2020-08-18 13:54:53 +02:00
public lineWidth: number
2020-12-23 17:26:55 +01:00
2020-08-18 13:54:53 +02:00
public drawLabelOptions: DrawTextFieldOptions
2020-12-23 17:26:55 +01:00
2020-08-18 13:54:53 +02:00
public label?: string
constructor(options: IDrawBoxOptions = {}) {
2020-12-23 17:26:55 +01:00
const {
boxColor, lineWidth, label, drawLabelOptions,
} = options;
this.boxColor = boxColor || 'rgba(0, 0, 255, 1)';
this.lineWidth = lineWidth || 2;
this.label = label;
2020-08-18 13:54:53 +02:00
const defaultDrawLabelOptions = {
anchorPosition: AnchorPosition.BOTTOM_LEFT,
2020-12-23 17:26:55 +01:00
backgroundColor: this.boxColor,
};
this.drawLabelOptions = new DrawTextFieldOptions({ ...defaultDrawLabelOptions, ...drawLabelOptions });
2020-08-18 13:54:53 +02:00
}
}
export class DrawBox {
public box: Box
2020-12-23 17:26:55 +01:00
2020-08-18 13:54:53 +02:00
public options: DrawBoxOptions
constructor(
box: IBoundingBox | IRect,
2020-12-23 17:26:55 +01:00
options: IDrawBoxOptions = {},
2020-08-18 13:54:53 +02:00
) {
2020-12-23 17:26:55 +01:00
this.box = new Box(box);
this.options = new DrawBoxOptions(options);
2020-08-18 13:54:53 +02:00
}
draw(canvasArg: string | HTMLCanvasElement | CanvasRenderingContext2D) {
2020-12-23 17:26:55 +01:00
const ctx = getContext2dOrThrow(canvasArg);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const { boxColor, lineWidth } = this.options;
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const {
x, y, width, height,
} = this.box;
ctx.strokeStyle = boxColor;
ctx.lineWidth = lineWidth;
ctx.strokeRect(x, y, width, height);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const { label } = this.options;
2020-08-18 13:54:53 +02:00
if (label) {
2020-12-23 17:26:55 +01:00
new DrawTextField([label], { x: x - (lineWidth / 2), y }, this.options.drawLabelOptions).draw(canvasArg);
2020-08-18 13:54:53 +02:00
}
}
2020-12-23 17:26:55 +01:00
}