Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

413
Visualizações
React useRef on Canvas getting null or undefined

I am trying to reference a canvas DOM element to make the width of it the same as its parent without messing with the scale of the canvas. When doing so I am getting a Uncaught TypeError: _canvasRef$current.getContext is not a function error and am not exactly sure how to fix it.

Ive console logged a few things just to make the app run but the issue is within the useEffect

import SignaturePad from 'react-signature-canvas'

const canvasRef = useRef<HTMLCanvasElement>(null)

useEffect(() => {
    const ctx: CanvasRenderingContext2D | null | undefined =
        canvasRef.current?.getContext('2d')
    const ctxContainer = document.getElementById('ctxContainer')

    console.log('ctx: ', ctx)
    // if (ctx && ctxContainer) {
    //     ctx.style.width = '100%'
    //     ctx.style.height = '100%'
    //     ctx.width = ctxContainer.clientWidth
    // }
}, [])

const save = () => {
    console.log('saved!')
}

console.log('canvasRef: ', canvasRef)

return (
    <div id={`ctxContainer`} className={'signatureInput__option-draw'}>
        <SignaturePad
            ref={canvasRef}
            canvasProps={{
                className: 'signatureInput__option-draw__canvas',
            }}
            onEnd={save}
        />
    </div>
)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try this.

Note that you may still need to do some changes to following code to full fill your full requirement ( such as event handling when the user change the screen sizes. ) The following code will fix the issue you are facing right now.

  useEffect(() => {
    if (canvasRef.current) {
      const canvas = canvasRef.current.getCanvas();
      const ctx = canvas.getContext('2d');

      // do something with the canvas ref
      if (ctx) {
        ctx.canvas.width = window.innerHeight;
        ctx.canvas.height = window.innerHeight;
      }
    }
  }, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

Try using getCanvas() . i dont think getContext() is provided with the package

function App() {
  const canvasRef = React.createRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    console.log(canvas.current);
    const ctx = canvas.getCanvas();
    const ctxContainer = document.getElementById("ctxContainer");

    console.log("ctx: ", ctx);
    if (ctx && ctxContainer) {
      ctx.style.width = "100%";
      ctx.style.height = "100%";
      ctx.width = ctxContainer.clientWidth;
    }
  }, []);

  const save = () => {
    console.log("saved!");
  };

  console.log("canvasRef: ", canvasRef);

  return (
    <div className="App">
      <div id={`ctxContainer`} className={"signatureInput__option-draw"}>
        <SignaturePad
          ref={(ref) => {
            canvasRef.current = ref;
          }}
          canvasProps={{
            className: "signatureInput__option-draw__canvas",
          }}
          onEnd={save}
        />
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda