Stage3D.js:用TypeScript与WebGL实现Stage3D API

在入门 WebGL 的过程中经常与 Stage3D 的 API 对比,后干脆把 Stage3D 的 API 实现出来了,也包括了 AS3 的数学库。

一些演示:

项目地址:

https://github.com/nshen/Stage3D.js

最简单的画三角形的代码如下 (效果演示) :

typescript

var canvas: HTMLCanvasElement = <HTMLCanvasElement>(
  document.getElementById("my-canvas")
);
 
stage3d = new stageJS.Stage3D(canvas);
stage3d.addEventListener(stageJS.events.Event.CONTEXT3D_CREATE, onCreated);
stage3d.requestContext3D();
 
function onCreated(e: stagl.events.Event): void {
  context3d = stage3d.context3D;
  context3d.configureBackBuffer(
    stage3d.stageWidth,
    stage3d.stageHeight,
    2,
    true
  );
 
  var program: stagl.Program3D = context3d.createProgram();
  program.upload("shader-vs", "shader-fs"); // shaders are in html file
  context3d.setProgram(program);
 
  var vertexBuffer: stagl.VertexBuffer3D = context3d.createVertexBuffer(3, 7);
  vertexBuffer.uploadFromVector(
    [
      -1, -1, 0, 1, 0, 0, 1, //xyz rgba
      1, -1, 0, 0, 1, 0, 1,
      0, 1, 0, 0, 0, 1, 1,
    ],
    0, 3
  );
 
  context3d.setVertexBufferAt(
    "va0",
    vertexBuffer,
    0,
    stagl.Context3DVertexBufferFormat.FLOAT_3
  ); // pos
  context3d.setVertexBufferAt(
    "va1",
    vertexBuffer,
    3,
    stagl.Context3DVertexBufferFormat.FLOAT_4
  ); // color
 
  var indexBuffer: stagl.IndexBuffer3D = context3d.createIndexBuffer(3);
  indexBuffer.uploadFromVector([0, 1, 2], 0, 3);
 
  context3d.clear(0.0, 0.0, 0.0, 1.0);
  context3d.drawTriangles(indexBuffer);
  context3d.present();
}

然后我直接拿第二个例子(a shooter game) 参加了 coding.net 的 HTML5 大赛,得了个优秀作品奖:)

战利品:

定制 Filco 机械键盘一个

全文完,如有帮助请支持我