Skip to content

Commit 84712de

Browse files
committed
Create drawRectangleFromPattern function to avoid allocation
1 parent 20c0c68 commit 84712de

2 files changed

Lines changed: 24 additions & 20 deletions

File tree

src/draw/draw-frame.ts

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { getScreenSize, mutateBoundariesFromPattern } from '../functions'
2-
import { Boundaries, State, ViewportNumber } from '../types'
2+
import { Boundaries, State, ViewportNumber, ViewportPattern } from '../types'
33
import { COLORS, DEBUG, MAX_DRAW_TIME_MS, MAX_PREVIEW_DRAW_CALLS, MIN_DEPTH } from './constants'
44
import PatternWorker from './patterns.worker?worker'
55
import { streamBatchedDrawablePatterns } from './stream-batched-drawable-patterns'
@@ -19,6 +19,28 @@ const measure = (f: () => void): number => {
1919
return performance.now() - start
2020
}
2121

22+
const drawRectangleFromPattern = (() => {
23+
// Optimization: Only allocate boundaries object once and mutate it in place.
24+
const boundaries: Boundaries<ViewportNumber> = {
25+
xMin: 0 as ViewportNumber,
26+
xMax: 0 as ViewportNumber,
27+
yMin: 0 as ViewportNumber,
28+
yMax: 0 as ViewportNumber,
29+
}
30+
31+
return function (ctx: CanvasRenderingContext2D, viewportPattern: ViewportPattern) {
32+
mutateBoundariesFromPattern(viewportPattern, boundaries)
33+
34+
// Draw rectangle.
35+
ctx.rect(
36+
boundaries.xMin,
37+
boundaries.yMin,
38+
boundaries.xMax - boundaries.xMin,
39+
boundaries.yMax - boundaries.yMin
40+
)
41+
}
42+
})()
43+
2244
export function* drawFrameIncrementally(
2345
ctx: CanvasRenderingContext2D,
2446
state: State
@@ -54,24 +76,8 @@ export function* drawFrameIncrementally(
5476
ctx.strokeStyle = COLORS[Math.min(COLORS.length - 1, depth)]!
5577
ctx.beginPath()
5678

57-
// Optimization: Only allocate boundaries object once and mutate it in place.
58-
const boundaries: Boundaries<ViewportNumber> = {
59-
xMin: 0 as ViewportNumber,
60-
xMax: 0 as ViewportNumber,
61-
yMin: 0 as ViewportNumber,
62-
yMax: 0 as ViewportNumber,
63-
}
64-
6579
for (const viewportPattern of patterns) {
66-
mutateBoundariesFromPattern(viewportPattern, boundaries)
67-
68-
// Draw rectangle.
69-
ctx.rect(
70-
boundaries.xMin,
71-
boundaries.yMin,
72-
boundaries.xMax - boundaries.xMin,
73-
boundaries.yMax - boundaries.yMin
74-
)
80+
drawRectangleFromPattern(ctx, viewportPattern)
7581
}
7682

7783
ctx.fill()

src/draw/stream-drawable-patterns.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,6 @@ const isValidPattern = (() => {
5353
}
5454
})()
5555

56-
57-
5856
/**
5957
* Creates a generator that yields drawable patterns one by one.
6058
*

0 commit comments

Comments
 (0)