iddan / react-native-canvas

A Canvas component for React Native
MIT License
981 stars 172 forks source link

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

Open aymeric75 opened 1 year ago

aymeric75 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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