-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrid.js
More file actions
80 lines (70 loc) · 2.03 KB
/
grid.js
File metadata and controls
80 lines (70 loc) · 2.03 KB
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
import { white } from "./colors.js";
import { FONT_WEIGHT_NORMAL, FONT } from "./constants.js";
export const makeGrid = (
canvasManager,
items,
{
itemWidth,
itemHeight,
edgeMargin = 32,
spaceBetweenH = 8,
spaceBetweenV = 12,
maxRows = 3,
}
) => {
const CTX = canvasManager.getContext();
const gridWidth = canvasManager.getWidth() - edgeMargin * 2;
const itemsPerRow = Math.floor(
(gridWidth + spaceBetweenH) / (itemWidth + spaceBetweenH)
);
const totalRows = Math.ceil(items.length / itemsPerRow);
const gridHeight =
(itemHeight + spaceBetweenV) * Math.min(totalRows, maxRows) - spaceBetweenV;
const drawItems = (drawFunc) => {
let truncatedIndex = false;
items.forEach((item, index) => {
const colIndex = index % itemsPerRow;
const rowIndex = Math.floor(index / itemsPerRow);
const lastRowItem =
rowIndex + 1 === maxRows && colIndex + 1 === itemsPerRow;
if (rowIndex < maxRows && !lastRowItem) {
CTX.save();
CTX.translate(
edgeMargin + itemWidth * colIndex + spaceBetweenH * colIndex,
itemHeight * rowIndex + spaceBetweenV * rowIndex
);
drawFunc(item, index);
CTX.restore();
} else if (!truncatedIndex) {
truncatedIndex = index;
}
});
if (truncatedIndex) {
CTX.save();
CTX.translate(
edgeMargin +
itemWidth * (itemsPerRow - 1) +
spaceBetweenH * (itemsPerRow - 1),
itemHeight * (maxRows - 1) + spaceBetweenV * (maxRows - 1)
);
CTX.fillStyle = "rgba(255, 255, 255, .2)";
CTX.beginPath();
CTX.roundRect(0, 0, itemWidth, itemHeight, 8);
CTX.closePath();
CTX.fill();
CTX.fillStyle = white;
CTX.font = `${FONT_WEIGHT_NORMAL} 14px ${FONT}`;
CTX.textAlign = "center";
CTX.fillText(
`+${items.length - truncatedIndex}`,
itemWidth / 2,
itemHeight / 2 + 4.5
);
CTX.restore();
}
};
return {
drawItems,
getHeight: () => gridHeight,
};
};