Part II: OpenGL To WebAssembly With React!

Nikhil Gupta
2 min readApr 7, 2021

--

Hey everyone,
I had talked about an end-to-end React App with WebAssembly in my previous article. This one intends to take it a step further by bringing in GPU rendering via OpenGL. So, let’s get started!

Basic WebGL Setup

This section takes you through the basic webgl setup within our react app.

We first need to add a canvas to our DOM.

<canvas id=”glCanvas” width=”100px” height=”100px” />

Now, we can create a draw function that extracts the WebGL context from this canvas and clears the canvas to red color.

With these changes, our index.js looks like below:

requestAnimationFrame request the browser to call the draw function at appropriate times.

On npm run start , you should now see a red square that has been rendered via WebGL.

OpenGL via WebAssembly

Next, let’s try to achieve the same using OpenGL. To accomplish this, we will add a function in our Sample Class that accepts a string (which will be the id of canvas in our DOM).

In our implementation, we will create a webgl context and then, call OpenGL APIs to clear the canvas like so:

With these out of the way, we can simply expose our render API as below:

Now, let’s update our core module with our latest changes:

emcc --bind bindings/SampleBindings.cpp -Icpp/ cpp/*.cpp -s WASM=1 -s MODULARIZE=1 -o Sample.js

Finally, we just need to go back to our draw function and update it to use this API via our core module:

On npm run start , you should again see the red square, but it has been rendered using WebAssembly. Now, you can start to bring-in your OpenGL code and see it running right in your browser :)

--

--