Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
2.7 kB
1
Indexable
Never
// Get the canvas element
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl');

// Define the vertices of the cube
const vertices = new Float32Array([
  // Front face
  -1, -1,  1,
   1, -1,  1,
   1,  1,  1,
  -1,  1,  1,

  // Back face
  -1, -1, -1,
   1, -1, -1,
   1,  1, -1,
  -1,  1, -1,

  // Left face
  -1, -1, -1,
  -1, -1,  1,
  -1,  1,  1,
  -1,  1, -1,

  // Right face
   1, -1, -1,
   1, -1,  1,
   1,  1,  1,
   1,  1, -1,

  // Top face
  -1,  1, -1,
   1,  1, -1,
   1,  1,  1,
  -1,  1,  1,

  // Bottom face
  -1, -1, -1,
   1, -1, -1,
   1, -1,  1,
  -1, -1,  1
]);

// Define the indices of the cube
const indices = new Uint16Array([
  0, 1, 2, 2, 3, 0, // Front face
  4, 5, 6, 6, 7, 4, // Back face
  8, 9, 10, 10, 11, 8, // Left face
  12, 13, 14, 14, 15, 12, // Right face
  16, 17, 18, 18, 19, 16, // Top face
  20, 21, 22, 22, 23, 20 // Bottom face
]);

// Create a WebGL buffer for the vertices
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

// Create a WebGL buffer for the indices
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

// Define the vertex shader
const vertexShaderSource = `
  attribute vec3 aVertexPosition;
  uniform mat4 uModelViewMatrix;
  uniform mat4 uProjectionMatrix;
  void main() {
    gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);
  }
`;

// Define the fragment shader
const fragmentShaderSource = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Red color
  }
`;

// Create and compile the vertex shader
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);

// Create and compile the fragment shader
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);

// Create a WebGL program
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);

// Get the uniform locations
const modelViewMatrixUniform = gl.getUniformLocation(program, 'uModelViewMatrix');
const projectionMatrixUniform = gl.getUniformLocation(program, 'uProjectionMatrix');

// Set up the perspective projection matrix
const fieldOfView = 45 * Math.PI / 180;
const aspectRatio = canvas.width /




Leave a Comment