本文主要介绍Vue与WebGL结合绘制三角形,这里用到新的知识点--缓冲区。本文部分代码源自《WebGL编程指南》。
这里创建了一个initBuffer的函数,用于操作缓冲区。代码如下
<template>
<div>
<canvas ref="myglCanvas" @mousedown="clickCanvas($event)" width="400" height="400"></canvas>
</div>
</template>
<script>
import Tools from "../lib/tools";
export default {
name: "glCanvas",
data() {
return {
VSHEADER_SOURCE: `attribute vec4 a_Position;
void main(){
gl_Position = a_Position;
}`,
FSHEADER_SOURCE: `void main(){
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}`,
points: [],
gl: null
};
},
methods: {
initBuffer: function(gl) {
let vertices = new Float32Array([0, 0.5, -0.5, -0.5, 0.5, -0.5]);
let n = 3; // The number of vertices
// Create a buffer object
let 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);
let a_Position = gl.getAttribLocation(gl.program, "a_Position");
if (a_Position < 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_Position, 2, gl.FLOAT, false, 0, 0);
// Enable the assignment to a_Position variable
gl.enableVertexAttribArray(a_Position);
return n;
},
setGL: function() {
this.gl = this.$refs.myglCanvas.getContext("webgl");
}
},
mounted() {
this.setGL();
Tools.initShaders(this.gl, this.VSHEADER_SOURCE, this.FSHEADER_SOURCE);
let n = this.initBuffer(this.gl);
if (n < 0) {
console.log("Failed to set the positions of the vertices");
return;
}
//设置背景色
this.gl.clearColor(0.0, 0.0, 0.0, 1);
//设置缓冲区颜色
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.gl.drawArrays(this.gl.TRIANGLES, 0, n);
}
};
</script>
<style scoped>
</style>
26行 设置三角形三个顶点的位置数组vertices,这里z默认为0;
29行 创建缓冲区vertexBuffer 对象;
36行 绑定缓冲区对象;
38行 将数据vertices写入缓冲区对象;
46行 将缓冲区对象分配给attribute对象;
48行 开启attribute对象;
运行效果
更多内容请扫码关注我的微信公众号,或者在微信里搜索公众号webgis学习,我会不定期更新自己的webgis方面的学习心得。