# WebGL绘制三角形

## 1. HelloTriangle.html

```<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>画一个三角形</title>
<canvas id="myGLCanvas" width="600" height="600">
</canvas>
</body>
<script type="text/javascript" src="HelloTriangle.js">
</script>
</html>```

## 2. HelloTriangle.js

```var gl;
function createGLContext(canvas) {
var names = ["webgl", "experimental-webgl"];
var context = null;
for (var i=0; i < names.length; i++) {
try {
context = canvas.getContext(names[i]); //获取webgl context绘图上下文
} catch(e) {}
if (context) {
break;
}
}
if (context) {
context.viewportWidth = canvas.width;
context.viewportHeight = canvas.height;
} else {
}
return context;
}

return null;
}
}

//顶点着色器程序
'attribute vec4 a_Position;\n' +
'void main() {\n' +
'  gl_Position = a_Position;\n' +
'  gl_PointSize = 10.0;\n' +
'}\n';

//片元着色器程序
'void main(){ \n' +
'    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n' + //gl_FragColor指定像素的颜色
'} \n';

}

}

function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.5,   -0.5, -0.5,   0.5, -0.5
]);
var n = 3; // The number of vertices

// Create a buffer object
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}

// Bind the buffer object to target
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
// Write date into the buffer object
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

var a_PosLocation = gl.getAttribLocation(gl.program, 'a_Position');
if (a_PosLocation < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
// Assign the buffer object to a_Position variable
gl.vertexAttribPointer(a_PosLocation, 2, gl.FLOAT, false, 0, 0);

// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_PosLocation);

return n;
}

function startup(){
var canvas = document.getElementById('myGLCanvas');//获取<canvas>元素
gl = createGLContext(canvas);

// Write the positions of vertices to a vertex shader
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}

// Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);

// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);

// Draw the rectangle
gl.drawArrays(gl.TRIANGLES, 0, n);
}```

## 参考代码

1. Hello Point——WebGL, http://www.cnblogs.com/idealer3d/p/3513838.html

88 篇文章19 人订阅

0 条评论

## 相关文章

12420

### UML学习-状态图

1.状态图概述 状态图（Statechart Diagram）主要用于描述一个对象在其生存期间的动态行为，表现为一个对象所经历的状态序列，引起状态转移的事件（E...

309100

### 伸手党福利-从零开始玩转图库

tinkerpop是一个图库标准，一个框架，学习图库，先从这个项目入手比较合适, neo4j, janusGraph只是它两个组件（图storage-engin...

1.2K30

340100

9620

2.8K70

74010

16320

13320

12230