|
| 1 | +await loadJs('https://unpkg.com/[email protected]') |
| 2 | + |
| 3 | +appendCss(` |
| 4 | +header { background-color: silver } |
| 5 | +header canvas { display: block } |
| 6 | +main { padding: 20px } |
| 7 | +main h2 a { font-size: 60%; } |
| 8 | +`) |
| 9 | + |
| 10 | +let themes = [ |
| 11 | + 'birds', 'cells', 'clouds', 'clouds2', 'dots', 'fog', 'globe', |
| 12 | + 'halo', 'net', 'rings', 'ripple', 'topology', 'trunk', 'waves', |
| 13 | +] |
| 14 | + |
| 15 | +// https://github.com/tengbao/vanta |
| 16 | +// https://vantajs.com |
| 17 | +let App = () => { |
| 18 | + let [theme, setTheme] = useState('birds') |
| 19 | + return ( |
| 20 | + <div> |
| 21 | + <VantaHeader theme={theme} /> |
| 22 | + <main> |
| 23 | + <h2>Vanta.js - <a target="_blank" href="https://github.com/tengbao/vanta">https://github.com/tengbao/vanta</a></h2> |
| 24 | + <ul>{themes.map(t => { |
| 25 | + return <li key={t}>{t === theme ? t : <a onClick={() => { |
| 26 | + setTheme(t) |
| 27 | + }}>{t}</a>}</li> |
| 28 | + })}</ul> |
| 29 | + </main> |
| 30 | + </div> |
| 31 | + ) |
| 32 | +} |
| 33 | + |
| 34 | +let VantaHeader = ({ theme }) => { |
| 35 | + let headerRef = useRef(null) |
| 36 | + |
| 37 | + useEffect(() => { |
| 38 | + let el = headerRef.current |
| 39 | + let destroy = loadVantaEffect(el, theme) |
| 40 | + return destroy |
| 41 | + }, [theme]) |
| 42 | + |
| 43 | + return <header ref={headerRef}></header> |
| 44 | +} |
| 45 | + |
| 46 | +let loadVantaEffect = (el, theme) => { |
| 47 | + let promise = (async () => { |
| 48 | + setRendering(true) |
| 49 | + if (['halo', 'topology'].includes(theme)) { |
| 50 | + await loadJs('https://unpkg.com/[email protected]/vendor/p5.min.js') |
| 51 | + } |
| 52 | + let method = theme.toUpperCase() |
| 53 | + if (!(window.VANTA && VANTA[method])) { |
| 54 | + await loadJs(`https://unpkg.com/[email protected]/dist/vanta.${theme}.min.js`) |
| 55 | + } |
| 56 | + let ret = VANTA[method]({ el }) |
| 57 | + let canvasHeight = el.querySelector('canvas').clientHeight |
| 58 | + el.style.height = `${canvasHeight}px` |
| 59 | + setRendering(false) |
| 60 | + return ret |
| 61 | + })() |
| 62 | + return () => { |
| 63 | + promise.then(ret => { ret.destroy() }) |
| 64 | + } |
| 65 | +} |
0 commit comments