forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBackgroundAnimation.tsx
More file actions
231 lines (199 loc) · 6.15 KB
/
BackgroundAnimation.tsx
File metadata and controls
231 lines (199 loc) · 6.15 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
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
import * as React from 'react'
import { usePrefersReducedMotion } from '~/utils/usePrefersReducedMotion'
import { twMerge } from 'tailwind-merge'
import { useMounted } from '~/hooks/useMounted'
import { useRouterState } from '@tanstack/react-router'
export function BackgroundAnimation() {
const canvasRef = React.useRef<HTMLCanvasElement>(null)
const prefersReducedMotion = usePrefersReducedMotion()
const mounted = useMounted()
const isHomePage = useRouterState({
select: (s) => s.location.pathname === '/',
})
React.useEffect(() => {
if (prefersReducedMotion !== false) {
return
}
const canvas = canvasRef.current
let morphDuration = 2000
const waitDuration = 1000 * 60 * 2
const easingFn = cubicBezier(0.645, 0.045, 0.355, 1.0)
if (canvas) {
const ctx = canvas.getContext('2d')!
let rafId: ReturnType<typeof requestAnimationFrame> | null = null
let timeout: ReturnType<typeof setTimeout> | null = null
let startTime = performance.now()
function createBlobs() {
return shuffle([
{
color: { h: 10, s: 100, l: 50 },
},
{
color: { h: 40, s: 100, l: 50 },
},
{
color: { h: 150, s: 100, l: 50 },
},
{
color: { h: 200, s: 100, l: 50 },
},
]).map((blob) => ({
...blob,
x: Math.random() * canvas!.width,
y: Math.random() * canvas!.height,
r: Math.random() * 500 + 700,
colorH: blob.color.h,
colorS: blob.color.s,
colorL: blob.color.l,
}))
}
function shuffle<T>(array: T[]) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
let startBlobs = createBlobs()
let currentBlobs = startBlobs
let targetBlobs: ReturnType<typeof createBlobs> = []
function resizeHandler() {
// Create an offscreen canvas and copy the current content
const offscreen = document.createElement('canvas')
offscreen.width = canvas!.width
offscreen.height = canvas!.height
offscreen.getContext('2d')!.drawImage(canvas!, 0, 0)
// Resize the main canvas
canvas!.width = window.innerWidth
canvas!.height = window.innerHeight
// Stretch and redraw the saved content to fill the new size
ctx.drawImage(offscreen, 0, 0, canvas!.width, canvas!.height)
}
function start() {
if (timeout) {
clearTimeout(timeout)
}
if (rafId) {
cancelAnimationFrame(rafId)
}
startBlobs = JSON.parse(JSON.stringify(currentBlobs))
targetBlobs = createBlobs()
startTime = performance.now()
animate()
}
function animate() {
ctx.clearRect(0, 0, canvas!.width, canvas!.height)
const time = performance.now() - startTime
const progress = time / morphDuration
const easedProgress = easingFn(progress)
// Draw the blobs
startBlobs.forEach((startBlob, i) => {
const targetBlob = targetBlobs[i]
currentBlobs[i].x = interpolate(
startBlob.x,
targetBlob.x,
easedProgress
)
currentBlobs[i].y = interpolate(
startBlob.y,
targetBlob.y,
easedProgress
)
const gradient = ctx.createRadialGradient(
currentBlobs[i].x,
currentBlobs[i].y,
0,
currentBlobs[i].x,
currentBlobs[i].y,
currentBlobs[i].r
)
currentBlobs[i].colorH = interpolate(
startBlob.colorH,
targetBlob.colorH,
easedProgress
)
currentBlobs[i].colorS = interpolate(
startBlob.colorS,
targetBlob.colorS,
easedProgress
)
currentBlobs[i].colorL = interpolate(
startBlob.colorL,
targetBlob.colorL,
easedProgress
)
gradient.addColorStop(
0,
`hsla(${currentBlobs[i].colorH}, ${currentBlobs[i].colorS}%, ${currentBlobs[i].colorL}%, 1)`
)
gradient.addColorStop(
1,
`hsla(${currentBlobs[i].colorH}, ${currentBlobs[i].colorS}%, ${currentBlobs[i].colorL}%, 0)`
)
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(
currentBlobs[i].x,
currentBlobs[i].y,
currentBlobs[i].r,
0,
Math.PI * 2
)
ctx.fill()
})
if (progress < 1) {
rafId = requestAnimationFrame(animate)
} else {
timeout = setTimeout(() => {
morphDuration = 4000
start()
}, waitDuration)
}
}
resizeHandler()
start()
window.addEventListener('resize', resizeHandler)
return () => {
if (rafId) {
cancelAnimationFrame(rafId)
}
if (timeout) {
clearTimeout(timeout)
}
window.removeEventListener('resize', resizeHandler)
}
}
}, [prefersReducedMotion])
return (
<div
className={twMerge(
'fixed inset-0 z-0 opacity-20 pointer-events-none',
'transition-opacity duration-[2s] ease-linear',
'[&+*]:relative',
mounted
? isHomePage
? 'opacity-10 dark:opacity-20'
: 'opacity-10 dark:opacity-20'
: 'opacity-0'
)}
>
<canvas ref={canvasRef} />
</div>
)
}
function cubicBezier(p1x: number, p1y: number, p2x: number, p2y: number) {
return function (t: number) {
const cx = 3 * p1x
const bx = 3 * (p2x - p1x) - cx
const ax = 1 - cx - bx
const cy = 3 * p1y
const by = 3 * (p2y - p1y) - cy
const ay = 1 - cy - by
const x = ((ax * t + bx) * t + cx) * t
const y = ((ay * t + by) * t + cy) * t
return y
}
}
function interpolate(start: number, end: number, progress: number) {
return start + (end - start) * progress
}