three.js简易教程

three.js(8)-BufferAttribute

2021-11-18  本文已影响0人  姜治宇

BufferAttribute是属性缓冲区对象,它不仅可以表示几何体的顶点位置数据,还可以表示颜色和法向量数据。

颜色数据

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>
</head>

<body>
    <div id="webgl"></div>
</body>

</html>
<script>
    var scene = new THREE.Scene();
    var axes = new THREE.AxesHelper(200);//50表示xyz轴的长度,红:x,绿:y,蓝:z
    scene.add(axes);//添加坐标轴
    var geometry = new THREE.BufferGeometry(); //声明一个缓冲几何体对象

    //类型数组创建顶点位置position数据
    var vertices = new Float32Array([
        0, 0, 0, //顶点1坐标
        50, 0, 0, //顶点2坐标
        0, 100, 0, //顶点3坐标

        0, 0, 10, //顶点4坐标
        0, 0, 100, //顶点5坐标
        50, 0, 10, //顶点6坐标
    ]);
    // 创建属性缓冲区对象
    var attribue = new THREE.BufferAttribute(vertices, 3); //3个为一组,作为一个顶点的xyz坐标
    // 设置几何体attributes属性的位置position属性
    geometry.attributes.position = attribue;
    //类型数组创建顶点颜色color数据
    var colors = new Float32Array([
        255, 255, 0, //顶点1颜色,黄色
        255, 0, 0, //顶点2颜色,红色
        0, 0, 0, //顶点3颜色,黑色

        0, 255, 0, //顶点4颜色,绿色
        0, 0, 255, //顶点5颜色,蓝色
        0, 255, 255, //顶点6颜色,青色
    ]);
    // 设置几何体attributes属性的颜色color属性
    geometry.attributes.color = new THREE.BufferAttribute(colors, 3); //3个为一组,表示一个顶点的颜色数据RGB
    //材质对象
    var material = new THREE.PointsMaterial({
        // 使用顶点颜色数据渲染模型,不需要再定义color属性
        // color: 0xff0000,
        vertexColors: THREE.VertexColors, //以顶点颜色为准
        size: 10.0 //点对象像素尺寸
    });
    // 点渲染模式  点模型对象Points
    var points = new THREE.Points(geometry, material); //点模型对象
    scene.add(points); //点对象添加到场景
    //创建相机对象
    var camera = new THREE.PerspectiveCamera(45, 2, 0.1, 2000);
    camera.position.set(300, 300, 100); //设置相机位置
    camera.lookAt(scene.position); //设置相机方向(指向的场景对象)


    /**
     * 创建渲染器对象
     */
    var renderer = new THREE.WebGLRenderer({
        antialias: true //消除锯齿
    });
    renderer.setSize(1000, 500);//设置渲染区域尺寸
    renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
    renderer.render(scene, camera);//渲染必须有场景和相机两个对象

    var cont = document.getElementById('webgl');
    cont.appendChild(renderer.domElement);
</script>
point.png

法向量数据

法向量表示垂直于平面的那个向量,是描述光线与平面关系的数据。我们如果要描述光线照射到平面的偏移角,需配合法向量来计算,请看图示。


n.png

也就是说,如果一个几何体没有法向量数据,那就只能表现没有打光的效果。

    var normals = new Float32Array([
        0, 0, 1, //顶点1法向量
        0, 0, 1, //顶点2法向量
        0, 0, 1, //顶点3法向量

        0, 1, 0, //顶点4法向量
        0, 1, 0, //顶点5法向量
        0, 1, 0, //顶点6法向量
    ]);
    // 设置几何体attributes属性的位置normal属性
    geometry.attributes.normal = new THREE.BufferAttribute(normals, 3);
上一篇 下一篇

猜你喜欢

热点阅读