📅  最后修改于: 2023-12-03 15:35:40.361000             🧑  作者: Mango
WebGL是一种基于OpenGL的3D图形库,用于开发交互式3D应用程序。本教程旨在向程序员介绍WebGL的基础知识和使用方法,包括WebGL渲染流程、顶点数据、着色器程序和纹理贴图等内容。
WebGL渲染流程包括以下步骤:
创建WebGL上下文:通过canvas元素获取WebGL上下文。
const canvas = document.getElementById('myCanvas');
const gl = canvas.getContext('webgl');
准备顶点数据:定义顶点位置、颜色和纹理坐标等数据。顶点数据需要按照一定顺序组织为缓冲区对象。
const vertices = [
0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
-0.5,-0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
0.5,-0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0
];
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
准备着色器程序:定义顶点着色器和片元着色器,并链接成一个着色器程序。
const vertexShaderSource = `
attribute vec3 aPosition;
attribute vec3 aColor;
attribute vec2 aTexCoord;
varying vec3 vColor;
varying vec2 vTexCoord;
void main() {
gl_Position = vec4(aPosition, 1.0);
vColor = aColor;
vTexCoord = aTexCoord;
}
`;
const fragmentShaderSource = `
precision mediump float;
uniform sampler2D uSampler;
varying vec3 vColor;
varying vec2 vTexCoord;
void main() {
gl_FragColor = texture2D(uSampler, vTexCoord) * vec4(vColor, 1.0);
}
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
定义顶点属性:定义每个顶点属性在缓冲区对象中的位置和数据类型等信息。
const aPositionLocation = gl.getAttribLocation(shaderProgram, 'aPosition');
gl.enableVertexAttribArray(aPositionLocation);
gl.vertexAttribPointer(aPositionLocation, 3, gl.FLOAT, false, 32, 0);
const aColorLocation = gl.getAttribLocation(shaderProgram, 'aColor');
gl.enableVertexAttribArray(aColorLocation);
gl.vertexAttribPointer(aColorLocation, 3, gl.FLOAT, false, 32, 12);
const aTexCoordLocation = gl.getAttribLocation(shaderProgram, 'aTexCoord');
gl.enableVertexAttribArray(aTexCoordLocation);
gl.vertexAttribPointer(aTexCoordLocation, 2, gl.FLOAT, false, 32, 24);
准备纹理贴图:加载纹理图像并创建纹理对象。
const image = new Image();
image.src = 'myTexture.png';
image.onload = function() {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.uniform1i(gl.getUniformLocation(shaderProgram, 'uSampler'), 0);
};
绘制图形:调用WebGL绘图函数绘制模型。
gl.drawArrays(gl.TRIANGLES, 0, 3);