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
相关产品推荐
相关产品推荐

