33// Initial ascii stuff (Look, I don't like creating a temporary canvas either, but...)
44
55const context = document . createElement ( 'canvas' ) . getContext ( '2d' )
6- context . font = getComputedStyle ( document . querySelector ( " .ascii" ) ) . font
6+ context . font = getComputedStyle ( document . querySelector ( ' .ascii' ) ) . font
77const charDimensions = context . measureText ( '.' ) // Monospace font assumed
88const charWidth = charDimensions . width
99const charHeight = charDimensions . fontBoundingBoxAscent
@@ -17,6 +17,29 @@ const seaTPS = 3;
1717const seaText = [ ]
1818const seaChars = [ '~' ]
1919
20+ function setOptimizedInterval ( element , render , tps ) {
21+ render ( )
22+ let handle = setInterval ( render , 1000 / tps )
23+ new IntersectionObserver ( ( entries ) => {
24+ entries . forEach ( ( entry ) => {
25+ if ( entry . intersectionRatio >= 0.05 ) {
26+ if ( handle === null ) {
27+ console . log ( 'Show animation on' , element )
28+ handle = setInterval ( render , 1000 / tps )
29+ }
30+ } else if ( handle != null ) {
31+ console . log ( 'Hide animation on' , element )
32+ clearInterval ( handle )
33+ handle = null
34+ }
35+ } )
36+ } , {
37+ root : null ,
38+ rootMargin : '0px' ,
39+ threshold : [ 0.05 , 0.06 ] ,
40+ } ) . observe ( element )
41+ }
42+
2043function randomSeaChar ( ) {
2144 return seaChars [ Math . floor ( Math . random ( ) * seaChars . length ) ]
2245}
@@ -33,5 +56,4 @@ function updateSea() {
3356 seaElement . innerText = seaText . join ( '' )
3457}
3558
36- updateSea ( ) ;
37- window . setInterval ( updateSea , 1000 / seaTPS )
59+ setOptimizedInterval ( seaElement , updateSea , seaTPS )
0 commit comments