前提条件和预期结果
目前只有少数的浏览器支持 WebGL ,请看我的另外一篇文章:Can I use WebGL?.
下面的例子是在 Windows 下的 Chrome 16/23 以及 Android 下的 Firefox 17 进行测试。如果你使用的是非兼容浏览器访问则会弹出一个警告。
图1:包含 Hello world 文本的动画的 WebGL 立方体
在兼容 HTML5 的浏览器上,你将会看到如下图所示的带动画效果的立方体:
图2: 示例运行的屏幕截图
该代码基于 Lighting in WebGL - How to simulate lighting effects in your WebGL context - 非常感谢这篇教程。在该实例初始运行时,动画的立方体是通过一个静态的 Bitmap 图形对象渲染的。
下面的代码演示如何在程序中动态的渲染文本:
XML/HTML Code复制内容到剪贴板
// TODO #1 New method to create a texture
function createCubeTexture(text) {
...
}
在这里使用 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); 是非常重要的,用来确保写文本时不会前后颠倒。剩下的就很容易理解了:
XML/HTML Code复制内容到剪贴板
// TODO #2 Assign the created texture for display
cubeTexture = createCubeTexture("Hello World!");
源码
// File #1: webgl-demo.htm
XML/HTML Code复制内容到剪贴板 <html> <head> <title>WebGL - Hello World!</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="sylvester.js" type="text/javascript"></script> <script src="glUtils.js" type="text/javascript"></script> <script src="webgl-demo.js" type="text/javascript"></script> <!-- Fragment shader program --> <script id="shader-fs" type="x-shader/x-fragment"> varying highp vec2 vTextureCoord; varying highp vec3 vLighting; uniform sampler2D uSampler; void main(void) { highp vec4 texelColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a); } </script> <!-- Vertex shader program --> <script id="shader-vs" type="x-shader/x-vertex"> attribute highp vec3 aVertexNormal; attribute highp vec3 aVertexPosition; attribute highp vec2 aTextureCoord; uniform highp mat4 uNormalMatrix; uniform highp mat4 uMVMatrix; uniform highp mat4 uPMatrix; varying highp vec2 vTextureCoord; varying highp vec3 vLighting; void main(void) { gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0); vTextureCoord = aTextureCoord; // Apply lighting effect highp vec3 ambientLight = vec3(0.6, 0.6, 0.6); highp vec3 directionalLightColor = vec3(0.5, 0.5, 0.75); highp vec3 directionalVector = vec3(0.85, 0.8, 0.75); highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0); highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0); vLighting = ambientLight + (directionalLightColor * directional); } </script> </head> <body onload="start()"> <canvas id="glcanvas" width="640" height="480"> Your browser doesn't appear to support the HTML5 <code><canvas></code> element. </canvas> </body> </html>郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答