本系列教程主要讲解利用WebGL开发网页版的三维图形程序。这里主要用到的OpenGL和FlyMath内容。本系列内容较难。要求学生对几何和编程有一定的了解。建议初三以上同学学习。
WebGL的使用必须要在HTML5基础上使用。他是把HTML5的CANVAS标签作为绘图上下文设备。因此我先创建一个简单的HTML5网页。就叫webgl.htm吧。
webgl.htm源文件
<html>
<head>
<title>WebGL_01:初始化环境</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<script>
function init_webgl()
{
}
</script>
</head>
<body>
<center>
<div>
<canvas id='webGL' width='600' height='400' style='border:1px solid #000000;'>
<b>浏览器不支持HTML5的Canvas标签.</b>
</canvas>
</div>
<div><button onclick='init_webgl();'>初始化WebGL</button></div>
</center>
</body>
</html>
这段代码很简单,显示一个canvas和一个button,下面我们给button添加初始化事件init_webgl()。
init_webgl()函数
function init_webgl()
{
var canvas = document.getElementById("webGL");
if(!canvas){
alert("获取<Canvas>标签失败!");
return;
}
//获取webGL统计图上下文
var gl_context = canvas.getContext('webgl',
{ antialias:true,
stencil:true});
if(!gl_context){
alert("获取WebGL上下文失败!");
}
//清空canvas的背景颜色
gl_context.clearColor(0,0,0.5,1);
//清空webgl颜色缓冲区里的内容
gl_context.clear(gl_context.COLOR_BUFFER_BIT);
}
这里要对getcontext函数说明下。这个函数第一个参数“webgl”是指出获取webgl设备的类型。之前还有其他参数可选,如”experimental-webgl“。当然现在都是选webgl这个参数。 后面跟的antialias和stencil是可选参数。你不设置,他们就是默认值。这些参数什么意思就不用我多说了。不懂查webgl手册。下面给出参数列表。
dictionary WebGLContextAttributes{
GLboolean alpha = true;
GLboolean depth = true;
GLboolean stencil = false;
GLboolean antialias = true;
GLboolean premultipliedAlpha = true;
GLboolean preserveDrawingBuffer = false;
GLboolean preferLowPowerToHighPerformance = false;
GLboolean failIfMajorPerformanceCaveat = false;
};