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/

相关推荐
wxiaohe19 小时前
【幼儿园识物】比大小启蒙资料PDF
其他
nikoni2311 小时前
828考研资料汇总
笔记·其他·硬件工程
JiNan.YouQuan.Soft1 天前
Linux下编译安装Kokkos
其他
红点租赁系统开发2 天前
小程序租赁系统开发指南与实现策略
其他
老陈头聊SEO3 天前
新手SEO指南如何快速入门与提升网站排名
其他
老陈头聊SEO3 天前
提炼关键词的力量:AI驱动下的SEO优化策略
其他
打工的小李3 天前
人才画像系统助力企业构建可持续发展的动态人才成长体系
其他
红点租赁系统开发3 天前
金融租赁系统的发展与全球化战略实施探讨
其他
这是我584 天前
C++打小怪游戏
c++·其他·游戏·visual studio·小怪·大型·怪物
NullPointerZZZ4 天前
vue3和element-plus笔记
其他