three.js GLBufferAttribute 介绍

75 阅读1分钟

GLBufferAttribute 是什么为什么要用 GLBufferAttribute

  • GLBufferAttribute 是 three.js与底层显示计算单元交互的API,不与three.js产生直接的连系
  • 使用方法与 BufferAttribute 类似,但是能够使用JS的原生方法提升某些应用场景的性能
  • GLBufferAttribute 也能通过 new THREE.BufferGeometry创建几何体

使用示例

// 获取 <canvas> 元素
const canvas = document.getElementById('myCanvas');

// 尝试获取 WebGL 上下文
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');

if (!gl) {
    console.error("WebGL 不被支持");
} else {
    console.log("WebGL 上下文已成功获取");
    const buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

    // 初始化缓冲区数据
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), gl.STATIC_DRAW);

    // 创建 GLBufferAttribute
    const glBufferAttribute = new THREE.GLBufferAttribute(buffer, 3);

    // 将 GLBufferAttribute 分配给几何体
    geometry.setAttribute('position', glBufferAttribute);
}