/
renderer.ts
129 lines (105 loc) · 2.67 KB
/
renderer.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import { QuerySelector } from '@svgdotjs/svg.js'
export enum Alignment {
LEFT = 'left',
MIDDLE = 'middle',
RIGHT = 'right',
}
export interface GraphcisElement {
width: number
height: number
x: number
y: number
remove: () => void
}
export abstract class Renderer {
protected constructor(protected container: QuerySelector | HTMLElement) {}
abstract line(
x1: number,
y1: number,
x2: number,
y2: number,
strokeWidth: number,
color: string,
classes?: string | string[],
): void
abstract size(width: number, height: number): void
abstract clear(): void
abstract remove(): void
abstract background(color: string): void
abstract title(title: string): void
abstract text(
text: string,
x: number,
y: number,
fontSize: number,
color: string,
fontFamily: string,
alignment: Alignment,
classes?: string | string[],
plain?: boolean,
): GraphcisElement
abstract circle(
x: number,
y: number,
diameter: number,
strokeWidth: number,
strokeColor: string,
fill?: string,
classes?: string | string[],
): GraphcisElement
abstract rect(
x: number,
y: number,
width: number,
height: number,
strokeWidth: number,
strokeColor: string,
classes?: string | string[],
fill?: string,
radius?: number,
): GraphcisElement
abstract triangle(
x: number,
y: number,
size: number,
strokeWidth: number,
strokeColor: string,
classes?: string | string[],
fill?: string,
): GraphcisElement
abstract pentagon(
x: number,
y: number,
size: number,
strokeWidth: number,
strokeColor: string,
fill?: string,
classes?: string | string[],
): GraphcisElement
protected static trianglePath(x: number, y: number, size: number): string {
return `M${x + size / 2} ${y} L${x + size} ${y + size} L${x} ${y + size}`
}
protected static ngonPath(x: number, y: number, size: number, edges: number): string {
let i: number
let a: number
const degrees = 360 / edges
const radius = size / 2
const points: [number, number][] = []
let curX = x
let curY = y
for (i = 0; i < edges; i += 1) {
a = i * degrees - 90
curX = radius + radius * Math.cos((a * Math.PI) / 180)
curY = radius + radius * Math.sin((a * Math.PI) / 180)
points.push([curX, curY])
}
const lines = points.reduce((acc, [posX, posY]) => `${acc} L${posX} ${posY}`, '')
return `M${curX} ${curY} ${lines}`
}
protected static toClassName(classes?: string | string[]): string {
if (!classes) {
return ''
}
return Array.isArray(classes) ? classes.join(' ') : classes
}
}