JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="mycanvas"></canvas>
CSS
#mycanvas {
border:2px solid #000000;
width:200px;
height:200px;
}
JavaScript
var VERTEX_SHADER =
"attribute vec3 vPosition;\n"+
"void main() {\n"+
" gl_Position = vec4(vPosition, 1.0);\n"+
"}\n";
var FRAGMENT_SHADER =
"precision mediump float;\n"+
"void main() {\n"+
" gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"+
"}\n";
var VERTS = [
// square, should be centered in canvas
// and at 1/4 the canvas dimensions
-0.5, -0.5, 1.0,
-0.5, 0.5, 1.0,
0.5, 0.5, 1.0,
0.5, -0.5, 1.0,
];
var INDICES = [
0,1,2,
0,2,3,
1,0,2,
2,0,3 // draw it multiple ways to make sure
// face culling doesn't make it disappear
];
var canvas = document.getElementById("mycanvas");
window.requestFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) { return window.setTimeout(callback, 1000/60); };
window.cancelFrame =
window.cancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout;
var vertexShader, fragmentShader, program;
var cubeVertBuffer, cubeIndicesBuffer;
var vertexPositionAttribute;
function Error3D(msg) {
console.log(msg);
alert("Error: " + msg);
return null;
}
function CreateShader(type, src) {
var shader;
shader = gl.createShader(type);
if(!shader) return null;
gl.shaderSource(shader, src);
gl.compileShader(shader);
return shader;
}
function Setup3D() {
try {
gl.viewport(0, 0, 200, 200);
gl.clearColor(1.0, 1.0, 1.0, 1.0);
vertexShader = CreateShader(gl.VERTEX_SHADER, VERTEX_SHADER);
if(!vertexShader) return Error3D("Error creating vertex shader");
fragmentShader = CreateShader(gl.FRAGMENT_SHADER,...