【问题标题】:react-native-canvas fillRect is not being drawnreact-native-canvas fillRect 没有被绘制
【发布时间】:2022-10-17 07:05:17
【问题描述】:

我正在尝试使用 react-native-canvas 在 react-native 中绘制一个简单的矩形,这是我的代码:

import React, { useRef, useEffect } from 'react';
import { SafeAreaView, Alert } from 'react-native';
import Canvas from 'react-native-canvas';

export default function App() {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
      const ctx = ref.current.getContext('2d');
      if (ctx) {
        ctx.fillStyle = 'red';
        ctx.fillRect(20, 20, 100, 100);
        Alert.alert('Canvas is ready');
      }
    }
  }, [ref]);

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <Canvas ref={ref} style={{ width: '100%', height: '100%', backgroundColor: 'black' }} />
    </SafeAreaView>
  );
}

程序正在进入if(ctx) 循环,因为正在显示Alert.alert(),但fillRect 和fillStyle 不起作用?

【问题讨论】:

    标签: javascript reactjs react-native canvas


    【解决方案1】:

    React Native Skia 文档中的This 实现对我有用。

    即,用 setTimeout 包装你的 if 函数

    【讨论】: