WebGL初探
HTML5出来已经有些时日了,对应的Canvas 2D已经有不少引擎对其支持了,虽然不是很完美,最起码做做小产品应该是可以的。 此时此刻,以往的经验告诉我们,目光不能短浅,一起要先于他人,基于硬件加速的渲染一定会更流畅,当然3D的局限性没有2D那么多,于是乎开起了WebGL的探寻之路。
首先来了解下WebGL。 WebGL使用基于OpenGL ES2的API 在浏览器上实现3D效果,使用HTML Canvas渲染3D,无需安装像FlashPlayer这样的插件。WebGL主要是用JavaScript编写,还有一些执行在GPU上的特效代码(着色器代码),WebGL元素可以混合其他HTML元素和页面其他部分或页面背景组合,下面来进入正题。
一、准备工作:
为了使用WebGL渲染3D你首先需要的是一个Canvas。下面的HTML片段建立一个Canvas设置onload事件,将用于初始化我们的WebGL。
<span style="font-size:12px;"><span style="font-family:Microsoft YaHei;"><</span><span style="font-family:SimSun;">body οnlοad="start()">
<canvas id="glcanvas" width="640" height="480">
Your browser doesn't appear to support the
<code><canvas></code> element.
</canvas>
</body></span></span>
<span style="font-size:12px;"><span style="font-family:SimSun;"><span style="white-space:pre"> </span>创建<span style="font-family: 'Microsoft YaHei';font-size:14px;">context对象</span></span></span>
<span style="font-size:12px;"><span style="font-family:SimSun;"><span style="font-family: 'Microsoft YaHei';font-size:14px;"></span></span></span><pre name="code" class="javascript">function initWebGL(canvas) {
gl = null;
try {
// Try to grab the standard context. If it fails, fallback to experimental.
gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
}
catch(e) {}
// If we don't have a GL context, give up now
if (!gl) {
alert("Unable to initialize WebGL. Your browser may not support it.");
gl = null;
}
return gl;
}
<span style="font-size:12px;"><span style="font-family:SimSun;"><span style="white-space:pre"> </span></span></span>
下面要获取WebGL的context对象,这个是渲染的上下文对象,包括了很多渲染接口。
var gl; // A global variable for the WebGL context
function start() {
var canvas = document.getElementById("glcanvas");
// Initialize the GL context
gl = initWebGL(canvas);
// Only continue if WebGL is available and working
if (gl) {
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Enable depth testing
gl.enable(gl.DEPTH_TEST);
// Near things obscure far things
gl.depthFunc(gl.LEQUAL);
// Clear the color as well as the depth buffer.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
}
最后调整视口
gl.viewport(0, 0, canvas.width, canvas.height);