This repository has been archived by the owner on Jun 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
/
Snow.js
121 lines (92 loc) · 2.66 KB
/
Snow.js
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
// @flow
import React, { useLayoutEffect, useRef, useState } from 'react'
import times from 'lodash/times'
import each from 'lodash/each'
import throttle from 'lodash/throttle'
export const isSnowTime = () => {
const now = new Date()
return process.env.SNOW_EVENT || (now.getMonth() === 11 && now.getDate() > 21)
}
function randomBetween(min, max, round) {
const num = Math.random() * (max - min + 1) + min
if (round) {
return Math.floor(num)
}
return num
}
function Flake(x, y) {
const maxWeight = 5
const maxSpeed = 3
this.x = x
this.y = y
this.r = randomBetween(0, 1)
this.a = randomBetween(0, Math.PI)
this.aStep = 0.01
this.weight = randomBetween(2, maxWeight)
this.alpha = this.weight / maxWeight / 2
this.speed = (this.weight / maxWeight) * maxSpeed
this.update = () => {
this.x += Math.cos(this.a) * this.r
this.a += this.aStep
this.y += this.speed
}
}
type Props = {
numFlakes: number,
}
const Snow = ({ numFlakes }: Props) => {
const canvasRef = useRef()
const containerRef = useRef()
const [dimension, setDimension] = useState({ width: 0, height: 0 })
useLayoutEffect(() => {
if (!containerRef.current) return () => {}
const updateDimension = () => {
if (containerRef.current) setDimension(containerRef.current.getBoundingClientRect())
}
const ro = new ResizeObserver(throttle(updateDimension, 250))
ro.observe(containerRef.current)
updateDimension()
return () => {
ro.disconnect()
}
}, [])
useLayoutEffect(() => {
const { width, height } = dimension
const canvas = canvasRef.current
if (!canvas) return () => {}
const ctx = canvas.getContext('2d')
const flakes = times(
numFlakes,
() => new Flake(randomBetween(0, width, true), randomBetween(0, height, true)),
)
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width
canvas.height = height
}
let loopId
const updateFlakes = () => {
ctx.clearRect(0, 0, width, height)
each(flakes, flake => {
flake.update()
ctx.beginPath()
ctx.arc(flake.x, flake.y, flake.weight, 0, 2 * Math.PI, false)
ctx.fillStyle = `rgba(255, 255, 255, ${flake.alpha})`
ctx.fill()
if (flake.y >= height) {
flake.y = -flake.weight
}
})
loopId = requestAnimationFrame(updateFlakes)
}
loopId = requestAnimationFrame(updateFlakes)
return () => {
cancelAnimationFrame(loopId)
}
}, [dimension, numFlakes])
return (
<div ref={containerRef} style={{ width: '100%', height: '100%' }}>
<canvas ref={canvasRef} />
</div>
)
}
export default Snow