gx
chenyc
2025-06-12 7b72ac13a83764a662159d4a49b7fffb90476ecb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* eslint-disable max-classes-per-file */
import { Box, IBoundingBox, IRect } from '../classes/index';
import { getContext2dOrThrow } from '../dom/getContext2dOrThrow';
import { AnchorPosition, DrawTextField, DrawTextFieldOptions, IDrawTextFieldOptions } from './DrawTextField';
 
export interface IDrawBoxOptions {
  boxColor?: string
  lineWidth?: number
  drawLabelOptions?: IDrawTextFieldOptions
  label?: string
}
 
export class DrawBoxOptions {
  public boxColor: string;
 
  public lineWidth: number;
 
  public drawLabelOptions: DrawTextFieldOptions;
 
  public label?: string;
 
  constructor(options: IDrawBoxOptions = {}) {
    const {
      boxColor, lineWidth, label, drawLabelOptions,
    } = options;
    this.boxColor = boxColor || 'rgba(0, 0, 255, 1)';
    this.lineWidth = lineWidth || 2;
    this.label = label;
 
    const defaultDrawLabelOptions = {
      anchorPosition: AnchorPosition.BOTTOM_LEFT,
      backgroundColor: this.boxColor,
    };
    this.drawLabelOptions = new DrawTextFieldOptions({ ...defaultDrawLabelOptions, ...drawLabelOptions });
  }
}
 
export class DrawBox {
  public box: Box;
 
  public options: DrawBoxOptions;
 
  constructor(
    box: IBoundingBox | IRect,
    options: IDrawBoxOptions = {},
  ) {
    this.box = new Box(box);
    this.options = new DrawBoxOptions(options);
  }
 
  draw(canvasArg: string | HTMLCanvasElement | CanvasRenderingContext2D) {
    const ctx = getContext2dOrThrow(canvasArg);
 
    const { boxColor, lineWidth } = this.options;
 
    const {
      x, y, width, height,
    } = this.box;
    ctx.strokeStyle = boxColor;
    ctx.lineWidth = lineWidth;
    ctx.strokeRect(x, y, width, height);
 
    const { label } = this.options;
    if (label) {
      new DrawTextField([label], { x: x - (lineWidth / 2), y }, this.options.drawLabelOptions).draw(canvasArg);
    }
  }
}