Certainly! Below is a simple HTML file that uses WebGL to render a 3D scene with a ball (sphere) in the center of a room. This example does not use any external libraries and is contained within a single file. The code includes comments to help you understand how it works.
Save the following code as an .html file and open it in a modern web browser that supports WebGL (like Chrome or Firefox).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Ball in a Room</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="glcanvas"></canvas>
<script>
// Get the canvas element
const canvas = document.getElementById('glcanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Initialize the WebGL context
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
// If WebGL is unavailable, display an error
if (!gl) {
alert('Unable to initialize WebGL. Your browser or machine may not support it.');
}
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec3 aVertexNormal;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec3 vLighting;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
// Apply lighting effect
highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);
highp vec3 directionalLightColor = vec3(0.9, 0.9, 0.9);
highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));
highp float directional = max(dot(aVertexNormal, directionalVector), 0.0);
vLighting = ambientLight + (directionalLightColor * directional);
}
`;
// Fragment shader program
const fsSource = `
varying highp vec3 vLighting;
void main() {
gl_FragColor = vec4(0.8, 0.2, 0.2, 1.0) * vec4(vLighting, 1.0);
}
`;
// Initialize a shader program
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' +
gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
// Creates a shader of the given type, uploads the source and compiles it
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' +
gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
// Initialize the shader program
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
vertexNormal: gl.getAttribLocation(shaderProgram, 'aVertexNormal'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
// Here's where we call the routine that builds all the objects we'll be drawing.
const buffers = initBuffers(gl);
// Draw the scene repeatedly
function render() {
drawScene(gl, programInfo, buffers);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
// Initialize the buffers we'll need
function initBuffers(gl) {
// Create a sphere
const sphere = createSphere(1, 30, 30);
// Create a buffer for the sphere's vertex positions.
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphere.positions), gl.STATIC_DRAW);
// Create a buffer for the sphere's normals.
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphere.normals), gl.STATIC_DRAW);
// Build the element array buffer; this specifies the indices
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(sphere.indices), gl.STATIC_DRAW);
return {
position: positionBuffer,
normal: normalBuffer,
indices: indexBuffer,
vertexCount: sphere.indices.length,
};
}
// Create a sphere
function createSphere(radius, latBands, longBands) {
const positions = [];
const normals = [];
const indices = [];
for (let latNumber = 0; latNumber <= latBands; latNumber++) {
const theta = latNumber * Math.PI / latBands;
const sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
for (let longNumber = 0; longNumber <= longBands; longNumber++) {
const phi = longNumber * 2 * Math.PI / longBands;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
const x = cosPhi * sinTheta;
const y = cosTheta;
const z = sinPhi * sinTheta;
normals.push(x, y, z);
positions.push(radius * x, radius * y, radius * z);
}
}
for (let latNumber = 0; latNumber < latBands; latNumber++) {
for (let longNumber = 0; longNumber < longBands; longNumber++) {
const first = (latNumber * (longBands + 1)) + longNumber;
const second = first + longBands + 1;
indices.push(first, second, first + 1);
indices.push(second, second + 1, first + 1);
}
}
return {
positions: positions,
normals: normals,
indices: indices,
};
}
// Draw the scene
function drawScene(gl, programInfo, buffers) {
gl.clearColor(0.6, 0.8, 1.0, 1.0); // Clear to sky blue
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix
const fieldOfView = 45 * Math.PI / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// Note: glmatrix.js has mat4.perspective
mat4.perspective(projectionMatrix,
fieldOfView,
aspect,
zNear,
zFar);
// Set the drawing position to the "identity" point
const modelViewMatrix = mat4.create();
// Move the drawing position to where we want to start drawing the sphere.
mat4.translate(modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[0.0, 0.0, -6.0]); // amount to translate
// Tell WebGL how to pull out the positions from the position buffer
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the normals from the normal buffer
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = true;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset);
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexNormal);
}
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix);
{
const offset = 0;
const vertexCount = buffers.vertexCount;
const type = gl.UNSIGNED_SHORT;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
// Simple matrix library (only the needed functions)
const mat4 = {
create: function() {
return new Float32Array(16).fill(0).map((v, i) => (i % 5 == 0 ? 1 : 0));
},
perspective: function(out, fovy, aspect, near, far) {
const f = 1.0 / Math.tan(fovy / 2);
const nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
},
translate: function(out, a, v) {
const x = v[0], y = v[1], z = v[2];
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
const a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3];
const a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7];
const a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11];
out[0] = a00;
out[1] = a01;
out[2] = a02;
out[3] = a03;
out[4] = a10;
out[5] = a11;
out[6] = a12;
out[7] = a13;
out[8] = a20;
out[9] = a21;
out[10] = a22;
out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
},
};
</script>
</body>
</html>
Explanation:
-
HTML Structure: The HTML file contains a <canvas> element where the WebGL rendering will take place.
-
WebGL Context Initialization: We obtain the WebGL rendering context from the canvas to start drawing with WebGL.
-
Shaders:
- Vertex Shader: Responsible for processing individual vertices. It calculates the position of each vertex and computes lighting effects.
- Fragment Shader: Calculates the color of each pixel. It applies the lighting calculated in the vertex shader.
-
Sphere Creation: A function createSphere generates the vertices, normals, and indices needed to render a sphere.
-
Rendering Loop: The render function calls drawScene in a loop using requestAnimationFrame to continuously render the scene.
-
Matrix Operations:
- Projection Matrix: Used to simulate the camera's perspective.
- Model-View Matrix: Transforms the sphere's position in the scene.
-
Simple Matrix Library: A minimal mat4 object provides necessary matrix functions (create, perspective, translate) for 3D transformations.
Notes:
- Since we cannot use external libraries, I've included minimal functions for matrix operations instead of using something like glMatrix.
- The scene is static, displaying a red sphere (ball) in the center of the room against a sky-blue background.
Running the Code:
-
Save the Code: Copy the code into a text editor and save it with an .html extension (e.g., 3d_ball.html).
-
Open in Browser: Open the file with a WebGL-compatible web browser (Chrome, Firefox, Edge).
-
Enjoy: You should see a red sphere in the center of the screen.
Customization Ideas:
- Add Interaction: Implement keyboard or mouse controls to rotate the camera around the sphere.
- Enhance the Room: Add walls, floor, or more objects to create a room setting.
- Animate: Make the sphere bounce or spin to bring the scene to life.
Feel free to explore and modify the code to suit your needs!