How iddan/react-native-canvas works
Project type and purpose
• This is an open‑source React Native library (“react‑native‑canvas”) that provides a Canvas component by embedding an HTML Canvas inside a React Native WebView and bridging the standard Canvas API across the native–JS boundary.
Main components
A. React Native Layer
– Example App / Consumer: Your React Native application that imports <Canvas /> from react‑native‑canvas.
– Canvas React Component (src/Canvas.js): Exposes a <Canvas /> component and handles props, refs, and lifecycle hooks.
B. Bridge / Messaging Layer
– react-native-webview Native Module: The native iOS/Android WebView view and its postMessage–onMessage plumbing.
– Message Bus (src/Bus.js): A JS event bus in the RN context that serializes Canvas API calls into messages.
– WebView Binders (src/webview-binders.js): Deserializes inbound messages from RN, routes them to the correct proxy object in the WebView context, and serializes return values back.
C. WebView (HTML/JS) Layer
– index.html / index.html.js: The HTML shell loaded into the WebView, which in turn loads webview.js.
– webview.js: Bootstraps the Canvas API proxies in the WebView’s global scope and wires up window.onMessage to your Binders.
– Canvas API Proxies (src/CanvasRenderingContext2D.js, src/CanvasGradient.js, src/Image.js, src/Path2D.js, src/ImageData.js): Implement Canvas and related APIs, proxying method calls to the actual DOM <canvas> element.
– HTML Canvas Element: The real <canvas> in the WebView’s DOM that executes drawing commands.
D. Support Modules
– autoscale-canvas.ts: A helper to scale the canvas for device pixel ratios.
– bundle-html.js: Bundles the HTML/JS resources for deployment.
Relationships and data flow
• Developer calls canvas.getContext("2d") in React Native →
→ Canvas Component invokes Bus.send(“getContext”, …) →
→ postMessage (via react‑native‑webview) to WebView →
→ WebView Binders receive message, look up the proxy object, call underlying CanvasRenderingContext2D method on real <canvas> →
→ If the method returns a value (e.g. toDataURL()), Binders serialize it and postMessage it back →
→ Bus receives it, resolves the Promise in RN, developer code continues.
Architectural patterns and design principles
– Facade/Adapter Pattern: Canvas.js and CanvasRenderingContext2D.js expose the standard HTML Canvas API to RN code, hiding the underlying WebView complexity.
– Message Bus / Proxy RPC: Bus.js centralizes message serialization; each Canvas API call is a remote procedure call over postMessage.
– Separation of Concerns: RN component (UI & props) is decoupled from WebView environment (actual rendering).
Detailed capture
– Illustrate the Bus.js API registry (mapping method names to message IDs).
– Optionally annotate the autoscale-canvas utility’s role in initializing the real <canvas> dimensions.