Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

background-animation.tsx

224 lines5.9 KB

1import * as React from 'react'
2import { twMerge } from 'tailwind-merge'
3​
4import { useMounted } from '../hooks/use-mounted'
5import { usePrefersReducedMotion } from '../hooks/use-preferred-reduced-motion'
6​
7export function BackgroundAnimation() {
8 const canvasRef = React.useRef<HTMLCanvasElement>(null)
9 const prefersReducedMotion = usePrefersReducedMotion()
10 const mounted = useMounted()
11 const isHomePage = false
12​
13 React.useEffect(() => {
14 if (prefersReducedMotion !== false) {
15 return
16 }
17​
18 const canvas = canvasRef.current
19​
20 let morphDuration = 2000
21 const waitDuration = 1000 * 60 * 2
22​
23 const easingFn = cubicBezier(0.645, 0.045, 0.355, 1.0)
24​
25 if (canvas) {
26 const ctx = canvas.getContext('2d')!
27​
28 let rafId: ReturnType<typeof requestAnimationFrame> | null = null
29 let timeout: ReturnType<typeof setTimeout> | null = null
30 let startTime = performance.now()
31​
32 function createBlobs() {
33 return shuffle([
34 {
35 color: { h: 10, s: 100, l: 50 },
36 },
37 {
38 color: { h: 40, s: 100, l: 50 },
39 },
40 {
41 color: { h: 150, s: 100, l: 50 },
42 },
43 {
44 color: { h: 200, s: 100, l: 50 },
45 },
46 ]).map((blob) => ({
47 ...blob,
48 x: Math.random() * canvas!.width,
49 y: Math.random() * canvas!.height,
50 r: Math.random() * 500 + 700,
51 colorH: blob.color.h,
52 colorS: blob.color.s,
53 colorL: blob.color.l,
54 }))
55 }
56​
57 function shuffle<T>(array: T[]) {
58 for (let i = array.length - 1; i > 0; i--) {
59 const j = Math.floor(Math.random() * (i + 1))
60 ;[array[i], array[j]] = [array[j], array[i]]
61 }
62 return array
63 }
64​
65 let startBlobs = createBlobs()
66 let currentBlobs = startBlobs
67 let targetBlobs: ReturnType<typeof createBlobs> = []
68​
69 function resizeHandler() {
70 // Create an offscreen canvas and copy the current content
71 const offscreen = document.createElement('canvas')
72 offscreen.width = canvas!.width
73 offscreen.height = canvas!.height
74 offscreen.getContext('2d')!.drawImage(canvas!, 0, 0)
75​
76 // Resize the main canvas
77 canvas!.width = window.innerWidth
78 canvas!.height = window.innerHeight
79​
80 // Stretch and redraw the saved content to fill the new size
81 ctx.drawImage(offscreen, 0, 0, canvas!.width, canvas!.height)
82 }
83​
84 function start() {
85 if (timeout) {
86 clearTimeout(timeout)
87 }
88 if (rafId) {
89 cancelAnimationFrame(rafId)
90 }
91​
92 startBlobs = JSON.parse(JSON.stringify(currentBlobs))
93 targetBlobs = createBlobs()
94 startTime = performance.now()
95 animate()
96 }
97​
98 function animate() {
99 ctx.clearRect(0, 0, canvas!.width, canvas!.height)
100​
101 const time = performance.now() - startTime
102 const progress = time / morphDuration
103 const easedProgress = easingFn(progress)
104​
105 // Draw the blobs
106 startBlobs.forEach((startBlob, i) => {
107 const targetBlob = targetBlobs[i]
108​
109 currentBlobs[i].x = interpolate(
110 startBlob.x,
111 targetBlob.x,
112 easedProgress,
113 )
114 currentBlobs[i].y = interpolate(
115 startBlob.y,
116 targetBlob.y,
117 easedProgress,
118 )
119​
120 const gradient = ctx.createRadialGradient(
121 currentBlobs[i].x,
122 currentBlobs[i].y,
123 0,
124 currentBlobs[i].x,
125 currentBlobs[i].y,
126 currentBlobs[i].r,
127 )
128​
129 currentBlobs[i].colorH = interpolate(
130 startBlob.colorH,
131 targetBlob.colorH,
132 easedProgress,
133 )
134 currentBlobs[i].colorS = interpolate(
135 startBlob.colorS,
136 targetBlob.colorS,
137 easedProgress,
138 )
139 currentBlobs[i].colorL = interpolate(
140 startBlob.colorL,
141 targetBlob.colorL,
142 easedProgress,
143 )
144​
145 gradient.addColorStop(
146 0,
147 `hsla(${currentBlobs[i].colorH}, ${currentBlobs[i].colorS}%, ${currentBlobs[i].colorL}%, 1)`,
148 )
149 gradient.addColorStop(
150 1,
151 `hsla(${currentBlobs[i].colorH}, ${currentBlobs[i].colorS}%, ${currentBlobs[i].colorL}%, 0)`,
152 )
153​
154 ctx.fillStyle = gradient
155 ctx.beginPath()
156 ctx.arc(
157 currentBlobs[i].x,
158 currentBlobs[i].y,
159 currentBlobs[i].r,
160 0,
161 Math.PI * 2,
162 )
163 ctx.fill()
164 })
165​
166 if (progress < 1) {
167 rafId = requestAnimationFrame(animate)
168 } else {
169 timeout = setTimeout(() => {
170 morphDuration = 4000
171 start()
172 }, waitDuration)
173 }
174 }
175​
176 resizeHandler()
177 start()
178 window.addEventListener('resize', resizeHandler)
179​
180 return () => {
181 if (rafId) {
182 cancelAnimationFrame(rafId)
183 }
184 if (timeout) {
185 clearTimeout(timeout)
186 }
187 window.removeEventListener('resize', resizeHandler)
188 }
189 }
190 }, [prefersReducedMotion])
191​
192 return (
193 <div
194 className={twMerge(
195 'fixed inset-0 z-0 opacity-20 pointer-events-none',
196 'transition-opacity duration-[2s] ease-linear',
197 '[&+*]:relative',
198 mounted
199 ? isHomePage
200 ? 'opacity-10 dark:opacity-20'
201 : 'opacity-10 dark:opacity-20'
202 : 'opacity-0',
203 )}
204 >
205 <canvas ref={canvasRef} />
206 </div>
207 )
209​
210function cubicBezier(_p1x: number, p1y: number, _p2x: number, p2y: number) {
211 return function (t: number) {
212 const cy = 3 * p1y
213 const by = 3 * (p2y - p1y) - cy
214 const ay = 1 - cy - by
215​
216 const y = ((ay * t + by) * t + cy) * t
217​
218 return y
219 }
221​
222function interpolate(start: number, end: number, progress: number) {
223 return start + (end - start) * progress