Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getcontext of a canvas gives TypeError: canvas.getContext is not a function #300

Open
aymeric75 opened this issue Oct 31, 2022 · 2 comments

Comments

@aymeric75
Copy link

Hello,

I need to retrieve the context of a canvas, here is what I have tried:

import React, { Component } from 'react';
import Canvas from 'react-native-canvas';
import { View } from 'react-native';


class MyCanva extends Component {
  handleCanvas = (canvas) => {
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'purple';
  }
  render() {
    return (
      <Canvas ref={this.handleCanvas}/>
    )
  }
}

export default function somefunction() {
  
  let canvas = new MyCanva();
  const context = canvas.getContext('2d');
  
  return (
    <View>
    </View>
  )
}

But it gives this error:
ERROR TypeError: canvas.getContext is not a function. (In 'canvas.getContext('2d')', 'canvas.getContext' is undefined)

Any idea where this comes from ?

Thanks

@Noa-Trachez
Copy link

Noa-Trachez commented Nov 7, 2022

Use this way

export const Test = () => {

  const canvasRef = useRef(null);

  useEffect(() => {
    if (canvasRef.current) {
      const canvas = canvasRef.current;
      const context = canvas.getContext('2d');
      context.fillStyle = 'blue';
      context.fillRect(0, 0, 100, 100);
    }
  }, [canvasRef]);

  return (
    <Canvas ref={canvasRef}/>
  )
}

function App() {
  return (
    <Test />
  )
}

@BraveEvidence
Copy link

This might help https://www.youtube.com/watch?v=wKr1kxNccgo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants