Appearance
上一篇文章我们介绍了什么是点模型,并且在页面上绘制出了不同的点,这一篇介绍下线模型
线模型Line渲染顶点数据
下面代码是把几何体作为线模型Line的参数,你会发现渲染效果是从第一个点开始到最后一个点,依次连成线。
js
// 线材质对象
const material = new THREE.LineBasicMaterial({
color: 0xff0000 //线条颜色
});
// 创建线模型对象
const line = new THREE.Line(geometry, material);线模型LineLoop、LineSegments
threejs线模型除了Line,还提供了 LineLoop、 LineSegments,区别在于绘制线条的规则不同。
js
// 闭合线条
const line = new THREE.LineLoop(geometry, material);
//非连续的线条
const line = new THREE.LineSegments(geometry, material);效果
代码实现
js
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 创建一个模型
const geometry = new THREE.BufferGeometry(); //创建一个几何体对象
//类型数组创建顶点数据
const 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坐标
]);
// 创建属性缓冲区对象
const attribue = new THREE.BufferAttribute(vertices, 3); //3个为一组,表示一个顶点的xyz坐标
// 设置几何体attributes属性的位置属性
geometry.attributes.position = attribue;
// 线条渲染模式
const material = new THREE.LineBasicMaterial({
color: 0xffff00 //线条颜色
}); //材质对象
// 创建线模型对象 构造函数:Line、LineLoop、LineSegments
const line = new THREE.Line(geometry, material); //线条模型对象
//场景
const scene = new THREE.Scene();
scene.add(line); //模型对象添加到场景中
//辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);
//光源设置
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(100, 60, 50);
scene.add(directionalLight);
const ambient = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambient);
//渲染器和相机
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
camera.position.set(292, 223, 185);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
// 渲染循环
function render() {
renderer.render(scene, camera);
requestAnimationFrame(render);
}
render();
const controls = new OrbitControls(camera, renderer.domElement);
// 画布跟随窗口变化
window.onresize = function () {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
};