WebGL Hello World
by lmatonement
HTML
<html>
<head>
<script id="vertex" type="x-shader">
attribute vec2 aVertexPosition;
void main() {
gl_Position = vec4(aVertexPosition, 0.0, 1.0);
}
</script>
<script id="fragment" type="x-shader">
#ifdef GL_ES
precision highp float;
#endif
uniform vec4 uColor;
void main() {
gl_FragColor = uColor;
}
</script>
</head>
<body onload="init()">
<canvas id="mycanvas" width="400" height="250"></canvas>
</body>
</html>
JavaScript
var canvas, gl;
function init(){
canvas = document.getElementById("mycanvas");
gl = canvas.getContext("experimental-webgl");
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.0, 0.5, 1.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA);
var v = document.getElementById("vertex").firstChild.nodeValue;
var f = document.getElementById("fragment").firstChild.nodeValue;
var vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, v);
gl.compileShader(vs);
var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, f);
gl.compileShader(fs);
program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
var aspect = canvas.width / canvas.height;
itemSize = 2;
var vertices;
var count = 0;
setInterval(function(){
count+=0.03;
var x = .8;
var x = 1.6 * Math.cos(count) * Math.sin(count);
vertices = new Float32Array([
-x, x*aspect, x, x*aspect, x,-x*aspect,
-x, x*aspect, x,-x*aspect, -x,-x*aspect
]);
program.uColor = gl.getUniformLocation(program, "uColor");
program.aVertexPosition = gl.getAttribLocation(program,"aVertexPosition");
gl.useProgram(program);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
numItems = vertices.length / itemSize;
gl.uniform4fv(program.uColor, [0.0, 0.3, 0.0, 0.0]);
gl.enableVertexAttribArray(program.aVertexPosition);
gl.vertexAttribPointer(program.aVertexPosition, itemSize, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, numItems);
x = 0.3;
width = .1;
y = x*aspect;
vertices = new Float32Array([-x-width, y, -x+width, y, -x+width, -y, -x-width, y, -x+width, -y, -x-width, -y]);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
numItems = vertices.length /itemSize;
...