Created
November 1, 2020 03:48
-
-
Save buddyeorl/0681541e788e07af6b304cf65782328d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useRef} from 'react'; | |
const AudioGraph = ({dataArray})=>{ | |
const canvasRef = useRef(); | |
//this function updates the canvas reference with the current sound frequencies | |
const draw = () => { | |
//canvasRef is a ref created with useRef hook | |
canvasRef.current.getContext('2d').fillStyle = 'rgb(255, 255, 255,0.5)'; | |
canvasRef.current.getContext('2d').clearRect(0, 0, window.innerWidth, 100); | |
canvasRef.current.getContext('2d').lineWidth = 2; | |
let gradient = canvasRef.current.getContext('2d').createLinearGradient(0, 0, window.innerWidth, 0); | |
gradient.addColorStop("0", "magenta"); | |
gradient.addColorStop("0.2", "blue"); | |
gradient.addColorStop("0.5", "green"); | |
gradient.addColorStop("0.8", "blue"); | |
gradient.addColorStop("1.0", "green"); | |
canvasRef.current.getContext('2d').strokeStyle = gradient; | |
canvasRef.current.getContext('2d').beginPath(); | |
// dataArray is an array received from the audioCtx analyzer with the current audioBuffer frequencies, | |
//updates every 5ms | |
if (dataArray) { | |
let sliceWidth = window.innerWidth / dataArray.length; | |
let x = 0; | |
for (let i = 0; i < dataArray.length; i++) { | |
let y = (-(dataArray[i]) * (75 / 255)); | |
if (i === 0) { | |
canvasRef.current.getContext('2d').moveTo(x, y + 75); | |
} else { | |
canvasRef.current.getContext('2d').lineTo(x, y + 75); | |
} | |
x += sliceWidth; | |
} | |
} | |
canvasRef.current.getContext('2d').lineTo(window.innerWidth, 75); | |
canvasRef.current.getContext('2d').stroke(); | |
} | |
return(<canvas ref={canvasRef} width={window.innerWidth} height="100" />) | |
} | |
export default AudioGraph; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment