画线
假设您要绘制线或圆,而不是线框Mesh。首先,我们需要设置渲染器,场景和相机(请参阅创建场景页面)。
这是我们将使用的代码:
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 500 );
camera.position.set( 0, 0, 100 );
camera.lookAt( 0, 0, 0 );
var scene = new THREE.Scene();
接下来,我们将定义材料。对于线,我们必须使用LineBasicMaterial或LineDashedMaterial。
//create a blue LineBasicMaterial
var material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
材质之后,我们将需要带有一些顶点的Geometry或BufferGeometry(建议使用BufferGeometry,因为它的性能更高,但是为简单起见,我们将在此处使用Geometry):
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3( -10, 0, 0) );
geometry.vertices.push(new THREE.Vector3( 0, 10, 0) );
geometry.vertices.push(new THREE.Vector3( 10, 0, 0) );
请注意,在每对连续的顶点之间绘制了线,但是没有在第一个和最后一个顶点之间绘制线(该线未闭合)。
现在我们有了两条线和一种材料的点,我们可以将它们放在一起形成一条线。
var line = new THREE.Line( geometry, material );
剩下的就是将其添加到场景中并调用render。
scene.add( line );
renderer.render( scene, camera );
现在,您应该看到由两条蓝线组成的向上箭头。
完整代码如下:
<html> <head> <title>My first three.js app</title> <style> body { margin: 0; } canvas { 100%; height: 100% } </style> </head> <body> <script src="js/three.js"></script> <script> var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); var renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); //指定材质 var material = new THREE.LineBasicMaterial({ color: 0x0000ff }); //初始化顶点 var geometry = new THREE.Geometry(); geometry.vertices.push(new THREE.Vector3(0, 0, 0)); geometry.vertices.push(new THREE.Vector3(0, 1, 0)); geometry.vertices.push(new THREE.Vector3(1, 0, 0)); //初始化线 var line = new THREE.Line(geometry, material); scene.add(line); camera.position.z = 5; var animate = function () { requestAnimationFrame(animate); renderer.render(scene, camera); }; animate(); </script> </body> </html>