mirror of
https://github.com/gre/gl-react.git
synced 2026-01-18 16:16:59 +00:00
2.0 KiB
2.0 KiB
Hello GL
This minimal example shows the classical "Hello World" of OpenGL 2D drawing, showing a nice 2D gradient where:
- The RED component increases with the X position of the pixel.
- The GREEN component increases with the Y position of the pixel.
N.B. a GLSL fragment uses a "functional rendering" paradigm, which means you have to implement a
Position => Colorfunction.
<HelloGL width={256} height={171} />
Implementation
N.B.: In this series of examples, we will show the React Native version code, the React version is also available in the repository and is very similar (if not identical).
const React = require("react-native");
const GL = require("gl-react-native");
const shaders = GL.Shaders.create({
helloGL: {
frag: `
precision highp float;
varying vec2 uv; // This variable vary in all pixel position (normalized from vec2(0.0,0.0) to vec2(1.0,1.0))
void main () { // This function is called FOR EACH PIXEL
gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); // red vary over X, green vary over Y, blue is 50%, alpha is 100%.
}
`
}
});
module.exports = GL.createComponent(
({ width, height }) =>
<GL.View
shader={shaders.helloGL}
width={width}
height={height}
/>,
{ displayName: "HelloGL" });
A GL component is implemented in 2 parts:
- first, you need to implement a fragment shader in GLSL (OpenGL Shading Language).
Give it to
GL.Shaders.createand you have a backed object in return (likeStyleSheet.create). - second, you can render a
<GL.View>and pass-in the shader you have defined previously. Do not forget to give a width and height.
Improved version
Now, we can rewrite this code to make it more "generic" like this:
...
module.exports = GL.createComponent(
props =>
<GL.View
shader={shaders.helloGL}
{...props}
/>,
{ displayName: "HelloGL" });
That way, we can optionally provides width and height to flow in GL.View (we will see later the power of this).
