Home > Back-end >  .getContext is not a function ReactJs
.getContext is not a function ReactJs

Time:11-25

I'm trying to use GSAP to make a scrolling animation in my react application however I keep getting the error .getContext is not a function when I have linked it to the canvas.

my plan is to create a scrolling animation similar to a flip book sort of thing

any advice would be very much appreciated

thanks

import { useRef } from "react";
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";

function Landing() {
  const canvasRef = useRef();
  canvasRef.width = window.innerWidth;
  canvasRef.height = window.innerHeight;
  const context = canvasRef.getContext("2d");
  const frameCount = 230;

  const currentFrame = (index) =>
    `../../assets/landing-animations/${(index   1).toString()}.jpg`;
  const images = [];
  let ball = { frame: 0 };

  for (let i = 0; i < frameCount; i  ) {
    const img = new Image();
    img.src = currentFrame(i);
    images.push(img);
  }

  images[0].onload = render;

  function render() {
    context.clearRect(0, 0, canvasRef.width, canvasRef.height);
    context.drawImage(images[ball.frame]);
  }
  return (
    <div className="landing">
      <h1 className="landing__header">Welcome to my portfolio</h1>
      <canvas className="landing__canvas" ref={canvasRef}></canvas>;
    </div>
  );
}

export default Landing;

CodePudding user response:

Need to access the current since the reference to the node becomes accessible at the current attribute of the ref.

Additionally wrap this with useMemo to detect changes to canvasRef

const context = useMemo(() => canvasRef?.current.getContext("2d"), [canvasRef])

CodePudding user response:

You need to add .current to access the .getContext

canvasRef.current.getContext("2d")

Try to add useEffect and see the results

 useEffect(()=>{
     if(!!canvasRef){
       console.log(canvasRef.current.getContext("2d"))
     }
 },[canvasRef])
  • Related