import { useMemo , useCallback } from "react" ; import * as Selectors from "../selectors" ; import { useTypedSelector } from "../hooks" ; const PIXEL_DENSITY = 2 ; function sliceAverage ( dataArray , sliceWidth , sliceNumber ) { const start = sliceWidth * sliceNumber ; const end = start + sliceWidth ; let sum = 0 ; for ( let i = start ; i < end ; i ++ ) { sum += dataArray [ i ] ; } return sum / sliceWidth ; } export function usePaintOscilloscopeFrame ( { analyser , height , width , renderWidth , } ) { const colors = useTypedSelector ( Selectors . getSkinColors ) ; const bufferLength = analyser . fftSize ; const dataArray = useMemo ( ( ) => { return new Uint8Array ( bufferLength ) ; } , [ bufferLength ] ) ; return useCallback ( ( canvasCtx ) => { analyser . getByteTimeDomainData ( dataArray ) ; canvasCtx . lineWidth = PIXEL_DENSITY ; canvasCtx . strokeStyle = colors [ 18 ] ; const sliceWidth = Math . floor ( bufferLength / width ) * PIXEL_DENSITY ; const h = height ; canvasCtx . beginPath ( ) ; for ( let j = 0 ; j <= renderWidth ; j ++ ) { const amplitude = sliceAverage ( dataArray , sliceWidth , j ) ; const percentAmplitude = amplitude / 255 ; const y = ( 1 - percentAmplitude ) * h ; const x = j * PIXEL_DENSITY ; if ( x === 0 ) { canvasCtx . moveTo ( x , y ) ; } else { canvasCtx . lineTo ( x , y ) ; } } canvasCtx . stroke ( ) ; } , [ analyser , bufferLength , colors , dataArray , height , renderWidth , width ] ) ; }