JSFiddle - React, Tailwind, and code Playground
by Michal Vodicka
HTML
<script id="vshader" type="x-shader/x-vertex">
attribute float a_positionIndex;
attribute float a_normalIndex;
attribute vec4 a_pos;
uniform sampler2D u_positions;
uniform sampler2D u_normals;
uniform mat4 u_mvpMatrix;
uniform mat4 u_mvMatrix;
varying vec3 v_normal;
void main() {
vec3 position = texture2D(
u_positions, vec2(a_positionIndex, 0.5)).rgb;
vec3 normal = texture2D(
u_normals, vec2(a_normalIndex, 0.5)).rgb;
gl_Position = u_mvpMatrix * vec4(position, 1);
v_normal = (u_mvMatrix * vec4(normal, 0)).xyz;
}
</script>
<script id="fshader" type="x-shader/x-fragment">
precision mediump float;
uniform vec4 u_color;
uniform vec3 u_lightDirection;
varying vec3 v_normal;
</script>
<canvas id="default" width="400" height="400"></canvas>
JavaScript
var WebGLManager = function (opt_canvasId) {
var canvas = opt_canvasId ? document.getElementById(opt_canvasId) : document.createElement("canvas");
var wgl = canvas.getContext("webgl");
this.canvas = canvas;
this.wgl = wgl;
this.programs = [];
}
WebGLManager.prototype = {
createProgramFromScripts: function (vShaderId, fShaderId) {
var wgl = this.wgl;
var vShader = this._createShaderFromScript(vShaderId, wgl.VERTEX_SHADER);
var fShader = this._createShaderFromScript(vShaderId, wgl.FRAGMENT_SHADER);
var program = this._createProgram(vShader, fShader);
this.programs.push(program);
return this.programs.length - 1;
},
_createProgram: function (vShader, fShader) {
var wgl = this.wgl;
var program = wgl.createProgram();
wgl.attachShader(program, vShader);
wgl.attachShader(program, fShader);
wgl.linkProgram(program);
return program;
},
_createShaderFromScript: function (shaderId, type) {
var wgl = this.wgl;
var shaderScript = document.getElementById(shaderId);
var shaderSource = shaderScript.text;
var shader = wgl.createShader(type);
wgl.shaderSource(shader, shaderSource);
wgl.compileShader(shader);
return shader;
}
}
var visibleApp = new WebGLManager("default");