iddan / react-native-canvas

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

How do you get fillRect to occupy full dimensions? #306

Closed JordanHoffman closed 1 year ago

JordanHoffman commented 1 year ago
  useEffect(()=>{
    if (canvasRef.current) {
      const ctx = canvasRef.current.getContext('2d')
      const text = "My very educated mother just served us nine pizzas."
      ctx.font = "20px Arial"
      if (ctx) {
        ctx.fillStyle = "white"
        ctx.fillRect(0,0, canvasRef.current.width, canvasRef.current.height)
        ctx.fillStyle = "black"
        ctx.fillText(text, 0, 50)
      }
    }

  }, [canvasRef])

...

  <View style={{display: 'flex', flex: 1, width: '100%', height: 300}}>
    <Canvas ref={canvasRef} style={{width: '100%', height: '100%', backgroundColor: 'green'}} />
  </View>

canvas

Above is some code showing my main problem. I'm doing very basic experiments. Typically in a normal html canvas, you can set the fillRect to fill the entire canvas by using canvas.width and cavas.height parameters within it. But here in react native, that does not work. I create an initial canvas with a green background color. Then I attempt to update it to be fully filled with a white background and some text. I have attached an image which shows that my new fillRect is not occupying the whole canvas like I had hoped it would. My guess is this has to do with react native using dp instead of regular pixels or something like that? In any case, is there a solution to this, maybe something along the lines of converting one pixel type to another?

Younanator commented 1 year ago

Try using the useWindowDimensions hook

https://reactnative.dev/docs/usewindowdimensions

RinatRezyapov commented 1 year ago

Same. The area has same dimensions whatever I do. Knowing dimension of window is not a problem here, the problem is there is no way to set canvas dimension (width/height attr on canvas not working)

RinatRezyapov commented 1 year ago

This works for me:

  const { height, width } = useWindowDimensions();
  const handleCanvas = (canvas) => {
    if (!canvas) return;
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'purple';
    ctx.fillRect(0, 0, width, height);
  }
BraveEvidence commented 1 year ago

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