WebGL初探


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);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值