-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcanvas.ts
333 lines (304 loc) · 9.59 KB
/
canvas.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { clamp, identity } from 'lodash';
import { type PathEnd, type Point, type RGBAColor, type RGBColor } from '../lib/types';
/**
* This function draws a thick lines from "from" to "to" on the given ImageData, with no
* antialiasing. This is very useful to handle picking, since it is not possible to disable
* antialiasing with the native JavaScript canvas APIs.
*/
export function drawAliasedLine(
imageData: ImageData,
from: Point,
to: Point,
[r, g, b]: RGBColor | RGBAColor,
thickness: number,
drawOnBottom: boolean,
number: number = Math.ceil(thickness / 2)
): void {
if (from.x > to.x)
return drawAliasedLine(imageData, to, from, [r, g, b], thickness, drawOnBottom);
const width = imageData.width;
const height = imageData.height;
const dx = to.x - from.x;
const dy = to.y - from.y;
const len = Math.sqrt(dx * dx + dy * dy);
// Calculate perpendicular vector
const normX = -dy / len;
const normY = dx / len;
// Calculate the four corners of the rectangle
const halfThickness = number;
const corner1 = {
x: from.x + (+normX - dx / len) * halfThickness,
y: from.y + (+normY - dy / len) * halfThickness,
};
const corner2 = {
x: from.x + (-normX - dx / len) * halfThickness,
y: from.y + (-normY - dy / len) * halfThickness,
};
const corner3 = {
x: to.x + (-normX + dx / len) * halfThickness,
y: to.y + (-normY + dy / len) * halfThickness,
};
const corner4 = {
x: to.x + (+normX + dx / len) * halfThickness,
y: to.y + (+normY + dy / len) * halfThickness,
};
const ascending = from.y < to.y;
const top = ascending ? corner4 : corner1;
const left = ascending ? corner1 : corner2;
const right = ascending ? corner3 : corner4;
const bottom = ascending ? corner2 : corner3;
const xMin = clamp(Math.floor(left.x), 0, width);
const xMax = clamp(Math.ceil(right.x), 0, width);
const yMin = clamp(Math.floor(bottom.y), 0, height);
const yMax = clamp(Math.ceil(top.y), 0, height);
for (let y = yMin; y <= yMax; y++) {
const xMinRow = clamp(
y < left.y
? Math.floor(bottom.x + ((y - bottom.y) * (left.x - bottom.x)) / (left.y - bottom.y))
: Math.floor(left.x + ((y - left.y) * (left.x - top.x)) / (left.y - top.y)),
xMin,
xMax
);
const xMaxRow = clamp(
y < right.y
? Math.ceil(bottom.x + ((y - bottom.y) * (right.x - bottom.x)) / (right.y - bottom.y))
: Math.ceil(right.x + ((y - right.y) * (right.x - top.x)) / (right.y - top.y)),
xMin,
xMax
);
for (let x = xMinRow; x <= xMaxRow; x++) {
const index = (y * width + x) * 4;
if (!drawOnBottom || !imageData.data[index + 3]) {
imageData.data[index] = r;
imageData.data[index + 1] = g;
imageData.data[index + 2] = b;
imageData.data[index + 3] = 255;
}
}
}
}
/**
* This function takes an integer radius, and returns a flat matrix of 1s and 0s, where the 1s
* represent the pixels that are within the disc. The shapes are cached, to make it faster to draw
* a lot of times discs of the same radius.
*
* Here are some examples to make it clearer what the output should look like:
*
* getAliasedDiscShape(0);
* [1]
* getAliasedDiscShape(1);
* [0, 1, 0,
* 1, 1, 1,
* 0, 1, 0]
* getAliasedDiscShape(2);
* [0, 0, 1, 0, 0,
* 0, 1, 1, 1, 0,
* 1, 1, 1, 1, 1,
* 0, 1, 1, 1, 0,
* 0, 0, 1, 0, 0]
*/
const DISCS_CACHE: Map<number, Uint8Array> = new Map();
export function getAliasedDiscShape(radius: number): Uint8Array {
const cachedShape = DISCS_CACHE.get(radius);
if (cachedShape) return cachedShape;
const diameter = radius * 2 + 1;
const shape = new Uint8Array(diameter * diameter);
for (let dy = -radius; dy <= radius; dy++) {
for (let dx = -radius; dx <= radius; dx++) {
const distance = dx * dx + dy * dy;
if (distance <= radius * radius) {
const x = dx + radius;
const y = dy + radius;
shape[y * diameter + x] = 1;
}
}
}
DISCS_CACHE.set(radius, shape);
return shape;
}
/**
* This function draws an aliased disc, using a shape computed by getDiscShape.
*/
export function drawAliasedDisc(
imageData: ImageData,
{ x: centerX, y: centerY }: Point,
radius: number,
[r, g, b]: RGBColor | RGBAColor,
drawOnBottom: boolean
): void {
centerX = Math.round(centerX);
centerY = Math.round(centerY);
radius = Math.ceil(radius);
const { width, height } = imageData;
const discShape = getAliasedDiscShape(radius);
// Draw the disc on the imageData
const diameter = radius * 2 + 1;
for (let dy = -radius; dy <= radius; dy++) {
for (let dx = -radius; dx <= radius; dx++) {
const shapeIndex = (dy + radius) * diameter + (dx + radius);
if (discShape[shapeIndex] === 1) {
const x = centerX + dx;
const y = centerY + dy;
if (x >= 0 && x < width && y >= 0 && y < height) {
const index = (y * width + x) * 4;
if (!drawOnBottom || !imageData.data[index + 3]) {
imageData.data[index] = r;
imageData.data[index + 1] = g;
imageData.data[index + 2] = b;
imageData.data[index + 3] = 255;
}
}
}
}
}
}
export function drawAliasedRect(
imageData: ImageData,
{ x, y }: Point,
width: number,
height: number,
[r, g, b]: RGBColor | RGBAColor
) {
const xMin = clamp(x, 0, imageData.width);
const yMin = clamp(y, 0, imageData.height);
const xMax = clamp(x + width, 0, imageData.width);
const yMax = clamp(y + height, 0, imageData.height);
for (let i = xMin; i < xMax; i++) {
for (let j = yMin; j < yMax; j++) {
const index = (j * imageData.width + i) * 4;
imageData.data[index] = r;
imageData.data[index + 1] = g;
imageData.data[index + 2] = b;
imageData.data[index + 3] = 255;
}
}
}
/**
* This function draws a "stop" path extremity.
* That handles a path that stops or starts exactly in an operational points included in the line
* represented in the chart.
*/
const STOP_END_SIZE = 6;
export function drawPathStopExtremity(
ctx: CanvasRenderingContext2D,
timePixel: number,
spacePixel: number,
swapAxis: boolean
): void {
ctx.beginPath();
if (!swapAxis) {
ctx.moveTo(timePixel, spacePixel - STOP_END_SIZE / 2);
ctx.lineTo(timePixel, spacePixel + STOP_END_SIZE / 2);
} else {
ctx.moveTo(spacePixel - STOP_END_SIZE / 2, timePixel);
ctx.lineTo(spacePixel + STOP_END_SIZE / 2, timePixel);
}
ctx.stroke();
}
/**
* This function draws an "out" path extremity.
* That handles a path that leaves or joins the line represented in the chart.
*/
const OUT_END_SIZE = 12;
export function drawPathOutExtremity(
ctx: CanvasRenderingContext2D,
timePixel: number,
spacePixel: number,
swapAxis: boolean,
extremityType: 'from' | 'to',
pathDirection: 'up' | 'down'
): void {
let horizontalSign = extremityType === 'from' ? -1 : 1;
let verticalSign = (pathDirection === 'down' ? -1 : 1) * horizontalSign;
let controlX = timePixel + 4 * horizontalSign;
let controlY = spacePixel + (OUT_END_SIZE - 2) * verticalSign;
let x = timePixel;
let y = spacePixel;
if (swapAxis) {
[horizontalSign, verticalSign] = [verticalSign, horizontalSign];
[controlX, controlY] = [controlY, controlX];
[x, y] = [y, x];
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.bezierCurveTo(
controlX,
controlY,
controlX,
controlY,
x + OUT_END_SIZE * horizontalSign,
y + OUT_END_SIZE * verticalSign
);
ctx.stroke();
}
/**
* This function draws a path extremity.
*/
export function drawPathExtremity(
ctx: CanvasRenderingContext2D,
timePixel: number,
spacePixel: number,
swapAxis: boolean,
extremityType: 'from' | 'to',
pathDirection: 'up' | 'down',
pathEnd: PathEnd
): void {
if (pathEnd === 'out') {
drawPathOutExtremity(ctx, timePixel, spacePixel, swapAxis, extremityType, pathDirection);
} else {
drawPathStopExtremity(ctx, timePixel, spacePixel, swapAxis);
}
}
/**
*
* @param minT number timestamp
* @param maxT number timestamp
* @param timeRanges time frames (24h, 12h, 6h, …)
* @param gridlinesLevels width of the lines for each time frame
* @param formatter function to format de values inside the output object
* @returns Record<number, number>
* Keys are times in ms
* Values are the highest level on each time
*/
export function computeVisibleTimeMarkers<T>(
minT: number,
maxT: number,
timeRanges: number[],
gridlinesLevels: number[],
formatter: (level: number, i: number) => T = identity
) {
const result: Record<number, T> = {};
const minTLocalOffset = new Date(minT).getTimezoneOffset() * 60 * 1000;
timeRanges.forEach((range, i) => {
const gridlinesLevel = gridlinesLevels[i];
if (!gridlinesLevel) return;
let t = Math.floor((minT - minTLocalOffset) / range) * range + minTLocalOffset;
while (t <= maxT) {
if (t >= minT) {
result[t] = formatter(gridlinesLevel, i);
}
t += range;
}
});
return result;
}
/**
* To get crisp horizontal or vertical lines on a canvas, we must draw them as thin as possible, in
* terms of actual pixels on screen.
* The best way for this is:
* - To center lines 1, 3, 5... pixels wide in the middle of a pixel
* - To center lines 2, 4, 6... pixels wide between two pixels
* @param rawCoordinate Any input coordinate to fix
* @param lineWidth The width of the line to draw
* @param devicePixelRatio
*/
export function getCrispLineCoordinate(
rawCoordinate: number,
lineWidth: number,
devicePixelRatio = window.devicePixelRatio || 1
): number {
const centerOffset = lineWidth / 2;
return (
Math.round((rawCoordinate - centerOffset) * devicePixelRatio) / devicePixelRatio + centerOffset
);
}