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
|
import { RangeSelection, Selection } from "../../selection";
import { CellRef } from "../../types";
import { getRenderedCell, RenderedCell, RenderedGrid } from "./renderGrid";
export interface GridStyles {
bgFill: string;
borderStroke: string;
cellStroke: string;
cellValueFont: string;
cellValueLineHeight: string;
}
function excursion(ctx: CanvasRenderingContext2D, f: () => void) {
ctx.save();
f();
ctx.restore();
}
function fillBackground(
ctx: CanvasRenderingContext2D,
styles: GridStyles,
grid: RenderedGrid,
) {
ctx.clearRect(0, 0, grid.rect.width, grid.rect.height);
ctx.fillStyle = styles.bgFill;
ctx.fillRect(0, 0, grid.rect.width, grid.rect.height);
}
function strokeGrid(
ctx: CanvasRenderingContext2D,
styles: GridStyles,
grid: RenderedGrid,
) {
ctx.strokeStyle = styles.borderStroke;
ctx.strokeRect(0.5, 0.5, grid.rect.width - 1, grid.rect.height - 1);
}
function strokeGridLines(
ctx: CanvasRenderingContext2D,
styles: GridStyles,
grid: RenderedGrid,
) {
ctx.strokeStyle = styles.cellStroke;
grid.renderedRows.forEach((row, renderedRowIndex) => {
const isLastRow = renderedRowIndex === grid.renderedRows.length - 1;
row.renderedCells.forEach((cell, cellIndex) => {
const { topLeft, width, height } = cell.rect;
const isLastCell = cellIndex === row.renderedCells.length - 1;
ctx.strokeRect(
topLeft.x + 0.5,
topLeft.y + 0.5,
isLastCell ? width - 1 : width,
isLastRow ? height - 1 : height,
);
});
});
}
function drawCellValues(
ctx: CanvasRenderingContext2D,
styles: GridStyles,
grid: RenderedGrid,
) {
grid.renderedRows.forEach((row) =>
row.renderedCells.forEach((cell) => {
if (!cell.value) return;
ctx.fillStyle = "white";
ctx.textAlign = "center";
ctx.font = styles.cellValueFont;
ctx.fillText(
cell.value,
cell.rect.center.x,
cell.rect.center.y + parseInt(styles.cellValueLineHeight) / 4,
);
}),
);
}
export default function drawGrid(
ctx: CanvasRenderingContext2D,
styles: GridStyles,
grid: RenderedGrid,
) {
excursion(ctx, () => fillBackground(ctx, styles, grid));
excursion(ctx, () => strokeGridLines(ctx, styles, grid));
excursion(ctx, () => strokeGrid(ctx, styles, grid));
excursion(ctx, () => drawCellValues(ctx, styles, grid));
}
|