WebGl绘制多个图形

WebGl绘制多个图形

WebGl的接口方法刚接触时多少有些不适应,在绘制多个图形介绍前,有必要把这个理解一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 常见的写法1: 通过传入对象,操作对象
draw(handle, x, y, color);

// 常见写法2: 对象为全局对象,直接在方法中操作对象
var handle = ...
draw(...) {
handle.draw(...);
}

// 常见写法3: 这种写法很传统,偏老。但得承认效率高

var x, y, color;

function setX(value) {
x = value;
}

function setY(value) {
y = value;
}

function setColor(value) {
color = value;
}

function draw() {
handle(x, y, color);
}

WebGl使用的第三种方式,所以每次绘图都必须重新覆盖各个全局变量后绘制图片

示例代码

■ index.vs

1
2
3
4
5
6
attribute vec4 a_Position;
attribute float a_PointSize;
void main(){
gl_Position=a_Position;
gl_PointSize=a_PointSize;
}

■ index.fs 

1
2
3
4
5
precision mediump float;
uniform vec4 u_FragColor;
void main(){
gl_FragColor=u_FragColor;
}

■ index,js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import vsSource from '~/index.vs';
import fsSource from '~/index.fs';

const t = arr => arr.map(x => x / 200);
const createSquare = (width, height, start) => {
const [x, y] = start;
// prettier-ignore
return [
x , y,
x + width, y,
x, y + height,
x + width, y + height
];
};

const canvas = document.getElementById('webgl');
const gl = canvas.getContext('webgl');

// 创建顶点着色器对象
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
// 绑定资源
gl.shaderSource(vertexShader, vsSource);
// 编译着色器
gl.compileShader(vertexShader);

// 创建片段着色器对象
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
// 绑定资源
gl.shaderSource(fragmentShader, fsSource);
// 编译着色器
gl.compileShader(fragmentShader);

// 创建一个着色器程序
const glProgram = gl.createProgram();

// 把前面创建的二个着色器对象添加到着色器程序中
gl.attachShader(glProgram, vertexShader);
gl.attachShader(glProgram, fragmentShader);

// 把着色器程序链接成一个完整的程序
gl.linkProgram(glProgram);

// 使用这个完整的程序
gl.useProgram(glProgram);

// 定位变量位置
const a_Position = gl.getAttribLocation(glProgram, 'a_Position');

// prettier-ignore
const vtxData = [
createSquare(200,30, [-100,100]),
createSquare(30,200, [-100,-100]),
];

for (let i = 0; i < vtxData.length; i++) {
const arrVtx = new Float32Array(t(vtxData[i]));

const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, arrVtx, gl.STATIC_DRAW);
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);

const a_PointSize = gl.getAttribLocation(glProgram, 'a_PointSize');
gl.vertexAttrib1f(a_PointSize, 10.0);

const u_FragColor = gl.getUniformLocation(glProgram, 'u_FragColor');
gl.uniform4f(u_FragColor, 0.0, 0.6, 0.38, 1);

gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
#

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×