three.js 入门 画线

622 阅读2分钟

@[TOC](three.js 入门 画线) 写在前面: 加载three.js内容时,一定要创建一个服务然后加载,不然加载不了

画线

准备

	创建renderer(渲染器)、scene(场景)和camera(相机)
		//创建渲染器,并添加到body
		const renderer = new THREE.WebGLRenderer();
		renderer.setSize( window.innerWidth, window.innerHeight );
		document.body.appendChild( renderer.domElement );
		//添加相机 参数说明:(相机垂直视野角度,摄像机视锥体长宽比,摄像机视锥体近端面,摄像机视锥体远端面) 
		const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / 		window.innerHeight, 1, 500 );
		//相机位置设置
		camera.position.set( 0, 0, 100 );
		//相机观测方向
		camera.lookAt( 0, 0, 0 );
		//添加场景
		const scene = new THREE.Scene();

添加材质

LineBasicMaterial,LineDashedMaterial 对线来说拥有这两种材质
		const material = new THREE.LineBasicMaterial( 
			{ 
			color: 0x0000ff		//十六进制颜色 
		 	} );

确定顶点

因为线就是将一个一个点连接在一起的,我们需要先确定点
		//定义三个向量数组
		const points = [];
		points.push( new THREE.Vector3( - 10, 0, 0 ) );
		points.push( new THREE.Vector3( 0, 10, 0 ) );
		points.push( new THREE.Vector3( 10, 0, 0 ) );
		//把他们转为点
		const geometry = new THREE.BufferGeometry().setFromPoints( points );
		const line = new THREE.Line( geometry, material );	//将点和材质传入,绘制线
		
		scene.add( line );	//加入场景
		renderer.render( scene, camera );	//渲染

线的完整代码及效果

	这里是三个顶点绘制了两条线
 //创建渲染器,并添加到body
		const renderer = new THREE.WebGLRenderer();
		renderer.setSize( window.innerWidth, window.innerHeight );
		document.body.appendChild( renderer.domElement );
		//添加相机 参数说明:(相机垂直视野角度,摄像机视锥体长宽比,摄像机视锥体近端面,摄像机视锥体远端面) 
		const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / 		window.innerHeight, 1, 500 );
		//相机位置设置
		camera.position.set( 0, 0, 100 );
		//相机观测方向
		camera.lookAt( 0, 0, 0 );
		//添加场景
		const scene = new THREE.Scene();

        const material = new THREE.LineBasicMaterial( 
			{ 
			color: 0x0000ff		//颜色
		 	} );
        //定义三个向量数组
		const points = [];
		points.push( new THREE.Vector3( 0, 0, 0 ) );
		points.push( new THREE.Vector3( 0, 10, 0 ) );
		points.push( new THREE.Vector3( 10, 0, 0 ) );
		//把他们转为点
		const geometry = new THREE.BufferGeometry().setFromPoints( points );
		const line = new THREE.Line( geometry, material );	//将点和材质传入,绘制线
		
		scene.add( line );	//加入场景
		renderer.render( scene, camera );	//渲染