<!DOCTYPE html>
<html>
<head>
<title>WebGL Example</title>
</head>
<body>
<canvas id="glCanvas" width="640" height="480"></canvas>
<script>
// Get the canvas element
var canvas = document.getElementById("glCanvas");
// Initialize WebGL context
var gl = canvas.getContext("webgl");
if (!gl) {
console.error("WebGL not supported, falling back on experimental-webgl");
gl = canvas.getContext("experimental-webgl");
}
if (!gl) {
alert("Your browser does not support WebGL");
}
// Define the vertex positions
var vertices = new Float32Array([
0.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0
]);
// Create a buffer for the vertex positions
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// Define the colors for each vertex
var colors = new Float32Array([
1.0, 0.0, 0.0, 1.0, // Red
0.0, 1.0, 0.0, 1.0, // Green
0.0, 0.0, 1.0, 1.0 // Blue
]);
// Create a buffer for the vertex colors
var colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
// Define the indices for the triangle
var indices = new Uint16Array([0, 1, 2]);
// Create a buffer for the indices
var indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,
indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
indices, gl.STATIC_DRAW);
// Vertex shader program
var vertexShaderSource = `
attribute vec3 coordinates;
attribute vec4 color;
varying vec4 vColor;
void main(void) {
gl_Position = vec4(coordinates, 1.0);
vColor = color;
}
`;
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader,
vertexShaderSource);
gl.compileShader(vertexShader);
// Fragment shader program
var fragmentShaderSource = `
precision mediump float;
varying vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
var fragmentShader = gl.createShader(gl
.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader,
fragmentShaderSource);
gl.compileShader(fragmentShader);
// Create and use the WebGL program
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram,
vertexShader);
gl.attachShader(shaderProgram,
fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
// Bind the vertex buffer to the shader program
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coord);
// Bind the color buffer to the shader program
var color = gl.getAttribLocation(shaderProgram, "color");
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.vertexAttribPointer(color, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(color);
// Clear the canvas
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw the triangle
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.drawElements(gl.TRIANGLES,
indices.length, gl.UNSIGNED_SHORT, 0);
</script>
</body>
</html>