1 ) 使用 三角带 TRIANGLE_STRIP 绘制矩形
回顾一下之前的规律:
关键顶点绘制数据
const vertices = new Float32Array([
-0.2, 0.2,
-0.2,-0.2,
0.2, 0.2,
0.2,-0.2,
])
绘制: gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
2 ) 使用 三角带 TRIANGLE_FAN 绘制矩形
回顾一下之前的规律:
基于此,设计顶点关键数据
const vertices = new Float32Array([
-0.2, -0.2,
0.2, -0.2,
0.2, 0.2,
-0.2, 0.2
])
绘制: gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
3 )使用独立三角形,绘制矩形
绘制规律
顶点关键数据
const vertices = new Float32Array([
-0.2, 0.2,
-0.2, -0.2,
0.2, 0.2,
0.2, 0.2,
-0.2, -0.2,
0.2, -0.2
])
可以根据自己的需求,绘制各种各样的图形
1 )封装一个Poly 对象,用于绘制多边形
const defAttr = () => ({
gl: null,
vertices: [],
geoData: [],
size: 2,
attrName: 'a_Position',
count: 0,
types: ['POINTS'],
})
export default class Poly {
constructor(attr) {
Object.assign(this,defAttr(),attr)
this.init()
}
init() {
const { attrName, size, gl } = this;
if(!gl) return
const vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
this.updateBuffer()
const a_Position = gl.getAttribLocation(gl.program,attrName)
gl.vertexAttribPointer(a_Position, size, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)
}
addVertice(...params) {
this.vertices.push(...params)
this.updateBuffer()
}
popVertice() {
const { vertices, size }=this
const len = vertices.length
vertices.splice(len-size,len)
this.updateCount()
}
setVertice(ind,...params) {
const { vertices, size }=this
const i = ind * size
params.forEach((param,paramInd) => {
vertices[i+paramInd] = param
})
}
updateBuffer() {
const { gl,vertices } = this
this.updateCount()
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
}
updateCount() {
this.count = this.vertices.length / this.size
}
updateVertices(params) {
const { geoData } = this
const vertices = []
geoData.forEach(data => {
params.forEach(key => {
vertices.push(data[key])
})
})
this.vertices=vertices
}
draw(types = this.types) {
const { gl, count } = this
for(let type of types) {
gl.drawArrays(gl[type],0,count);
}
}
}
属性
方法
2 )应用1
const poly = new Poly({
gl,
vertices:[0, 0.2]
})
poly.draw(['POINTS'])
setTimeout(()=>{
poly.addVertice(-0.2, -0.1);
gl.clear(gl.COLOR_BUFFER_BIT);
poly.draw(['POINTS'])
}, 1000)
setTimeout(()=>{
gl.clear(gl.COLOR_BUFFER_BIT);
poly.draw(['POINTS','LINE_STRIP'])
}, 2000)
3 )应用2
// 实例化多边形
const poly = new Poly({
gl,
types:['POINTS','LINE_STRIP']
})
// 鼠标点击事件
canvas.addEventListener("click", (event) => {
const { x,y } = getMousePosInWebgl(event, canvas);
poly.addVertice(x,y);
gl.clear(gl.COLOR_BUFFER_BIT);
poly.draw();
});