You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-native-canvas中fillRect无法绘制的技术求助

解决react-native-canvas无法绘制矩形的问题

以下是针对该问题的有效解决步骤:

  • 异步获取Canvas上下文
    react-native-canvas的getContext方法实际返回Promise对象,同步获取会导致上下文未完全初始化——即便ctx不为空,后续绘制操作也无法生效,必须用async/await处理。

  • 确保Canvas加载完成
    可通过监听Canvas的onLoad事件,或在useEffect中异步执行绘制逻辑,避免因组件未完全渲染、尺寸未确定导致绘制内容不可见。

修改后的完整代码:

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);

  const drawRect = async () => {
    if (!ref.current) return;
    const ctx = await ref.current.getContext('2d');
    if (ctx) {
      // 可选:清除画布原有内容
      ctx.clearRect(0, 0, ref.current.width, ref.current.height);
      ctx.fillStyle = 'red';
      ctx.fillRect(20, 20, 100, 100);
      Alert.alert('Canvas绘制完成');
    }
  };

  useEffect(() => {
    drawRect();
  }, []);

  // 也可通过onLoad事件触发绘制,替换上方useEffect逻辑
  // return (
  //   <SafeAreaView style={{ flex: 1 }}>
  //     <Canvas ref={ref} onLoad={drawRect} style={{ width: '100%', height: '100%', backgroundColor: 'black' }} />
  //   </SafeAreaView>
  // );

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

额外注意事项:

  • 确认已正确安装并链接react-native-canvas依赖(iOS需执行pod install,安卓需检查gradle配置)
  • 若绘制内容仍不可见,可尝试给Canvas设置固定宽高(如width: 300, height: 300),排查是否为百分比尺寸计算导致的问题

内容的提问来源于stack exchange,提问作者risky last

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:36:08