WebGL: 几个入门小例子

本文通过WebGL例子,来帮助WebGL入门学习。

一、概述

WebGL (Web Graphics Library)是一组基于Open ES、在Web内渲染3D图形的Javascript APIs。

Ref. from Khronos Group: WebGL

WebGL™ is a cross-platform, royalty-free open web standard for a low-level 3D graphics API based on OpenGL ES, exposed to ECMAScript via the HTML5 Canvas element.

二、配置WebGL开发环境

三、例子1:绘制三角形

html 复制代码
<!DOCTYPE HTML>
<html lang="en">
	<head>
		<title>Draw a triangle</title>
		<meta charset="utf-8">
		<script type="text/javascript">
			var gl;
			var canvas;
			var shaderProgram;
			var vertexBuffer;
			function createGLContext(canvas)
			{
				var names = ["webgl", "experimental-webgl"];
				var context = null;
				for(var i = 0; i < names.length; i++)
				{
					try
					{
						context = canvas.getContext(names[i]);
					}
					catch(e)
					{
						if (context)
						{
							break;
						}
					}
				}
                if(context)
                {
                    context.viewportWidth = canvas.width;
                    context.viewportHeight = canvas.height;
                }
                else
                {
                    alert("Failed to create WebGL context!");
                }
                
                return context;
			}
            
            function loadShader(type, shaderSource)
            {
               var shader = gl.createShader(type);
               gl.shaderSource(shader, shaderSource);
               gl.compileShader(shader);
                
               if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
               {
                   alert("Error compiling shader" + gl.getShaderInfoLog(shader));
                   gl.deleteShader(shader);
                   return null
               }
                
               return shader;
            }
            
            function setupShaders()
            {
                var vertexShaderSource = 
                    "attribute vec3 aVertexPosition;				\n" +
                	"void main()									\n" + 
                	"{												\n" +
                    "	gl_Position = vec4(aVertexPosition, 1.0);	\n" + 
                    "}									            \n";
                
             	var fragmentShaderSource = 
                    "precision mediump float;						\n" +
                	"void main()									\n" + 
                	"{												\n" +
                    "	gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);	\n" + 
                    "}									            \n";
                
                var vertexShader = loadShader(gl.VERTEX_SHADER, vertexShaderSource);
                var fragmentShader = loadShader(gl.FRAGMENT_SHADER, fragmentShaderSource);
                
                shaderProgram = gl.createProgram();
                gl.attachShader(shaderProgram, vertexShader);
                gl.attachShader(shaderProgram, fragmentShader);
                
                gl.linkProgram(shaderProgram);
                
                if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
                {
                    alert("Failed to setup shaders!");
                }
                
                gl.useProgram(shaderProgram);
                
                shaderProgram.vertexPositionAttribute = 
                    gl.getAttribLocation(shaderProgram, "aVertexPosition");
            }
            
            function setupBuffers()
            {
                vertexBuffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
                
                var triangleVertices = [
                    0.0, 0.5, 0.0,
                    -0.5, -0.5, 0.0,
                    0.5, -0.5, 0.0
                ];
                gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleVertices), gl.STATIC_DRAW);
                vertexBuffer.itemSize = 3;
                vertexBuffer.numberOfItems = 3;
            }
            
            function draw()
            {
                gl.viewport(0,0, gl.viewportWidth, gl.viewportHeight);
                gl.clear(gl.COLOR_BUFFER_BIT);
                
                gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);
                gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);
                gl.drawArrays(gl.TRIANGLES, 0, vertexBuffer.numberOfItems);
            }

            function startup()
            {
                canvas = document.getElementById("myGLCanvas");
                gl = createGLContext(canvas);
                setupShaders();
                setupBuffers();
                gl.clearColor(0.0,0.0,0.0,1.0);

                draw();
            }
            
		</script>
	</head>
	<body onload="startup();">
		<canvas id="myGLCanvas" width="500" height="500"></canvas>
	</body>
</html>

参考资料

Andreas Anyuru. Professional WebGL Programming: Developing 3D Graphics for the Web.

Kouichi Matsuda, Rodger Lea. WebGL Programming Guide: Interactive 3D Graphics Programming with WebGL.

网络资料

WebGLhttps://www.khronos.org/webgl/

WebGL 2.0 Specificationhttps://registry.khronos.org/webgl/specs/latest/2.0/

Three.jshttps://threejs.org/

BabylonJShttps://www.babylonjs.com/

相关推荐
清涔秋风9 小时前
自动驾驶革命:从特斯拉到百度,谁将主宰未来交通?
其他
清涔秋风11 小时前
智能家居的未来:AI让生活更智能还是更复杂?
其他
清涔秋风1 天前
虚拟现实和增强现实技术,如何打造沉浸式体验?
其他
渊鱼L1 天前
Abaqus随机骨料过渡区孔隙三维网格插件:Random Agg ITZ Pore 3D (Mesh)
其他
KeithTsui2 天前
ZFC in LEAN 之 前集的等价关系(Equivalence on Pre-set)详解
开发语言·其他·算法·binder·swift
清涔秋风3 天前
太空旅游:科技能否让星辰大海变为现实?
其他
清涔秋风3 天前
社交媒体中的AI算法,对信息传播有什么影响?
其他
橙子家3 天前
专业术语简介【一】:没有银弹、加盐、毛刺、冒烟测试、热备
其他
打工的小李4 天前
信息化建设:驱动干部管理工作提质增效的新引擎
其他
快鲸AI-seo4 天前
搜索引擎算法更新对网站优化的影响与应对策略
其他