# three.js绘制直线

``````var p1 = new THREE.Vector3(50,10,20);
var p2 = new THREE.Vector3(10,40,30);
geometry.vertices.push(p1,p2);``````

``````var p3 = new THREE.Vector3(100,10,10);
var p4 = new THREE.Vector3(10,10,100);
var line2 = new THREE.LineCurve3(p3,p4);
let points = line2.getPoints(100);
geometry.setFromPoints(points);``````

``````var p5 = new THREE.Vector2(80,10);
var p6 = new THREE.Vector2(20,80);
var line3 = new THREE.LineCurve(p5,p6);
let points = line3.getPoints(100);
geometry.setFromPoints(points);``````

全部代码如下：

``````<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绘制二维三维直线</title>
<script src="../three.js"></script>
<script src="../OrbitControls.js"></script>
<body>
<script>
// 1,创建场景对象
var scene = new THREE.Scene();
// 2,创建普通模型对象
var geometry = new THREE.Geometry();
// getPoints是基类Curve的方法，返回一个vector2对象作为元素组成的数组
// setFromPoints方法从points中提取数据改变几何体的顶点属性vertices

//创建直线的方式有三种：
// 方式一 start (创建三维直线，使用 Vector3)
var p1 = new THREE.Vector3(50,10,20);
var p2 = new THREE.Vector3(10,40,30);
geometry.vertices.push(p1,p2);
// 方式一 end (创建三维直线，使用 Vector3)

// 方式二 start （创建三维直线，使用 Vector3, LineCurve3）
// var p3 = new THREE.Vector3(100,10,10);
// var p4 = new THREE.Vector3(10,10,100);
// var line2 = new THREE.LineCurve3(p3,p4);
// let points = line2.getPoints(100);
// geometry.setFromPoints(points);
// 方式二 end （创建三维直线，使用 Vector3, LineCurve3）

// 方式三  start （创建二维直线，使用 Vector2, LineCurve）
// var p5 = new THREE.Vector2(80,10);
// var p6 = new THREE.Vector2(20,80);
// var line3 = new THREE.LineCurve(p5,p6);
// let points = line3.getPoints(100);
// geometry.setFromPoints(points);
// 方式三  end （创建二维直线，使用 Vector2, LineCurve）

var material = new THREE.LineBasicMaterial({color:0xee00ff});
var line = new THREE.Line(geometry,material);
// 3，创建环境光对象
var ambient = new THREE.AmbientLight({color:0xffffff});
// 4，创建相机对象
var width = window.innerWidth;
var height = window.innerHeight;
var k = width / height;
var s = 200;
var camera = new THREE.OrthographicCamera(-s*k,s*k,s,-s,-2000,2000);
camera.position.set(200,300,200);
camera.lookAt(scene.position);
// 创建轴辅助对象
var axes_helper = new THREE.AxesHelper(500);
// 5，创建渲染器对象
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width,height);
document.body.appendChild(renderer.domElement);
function render(){
renderer.render(scene,camera);
}
render();
// 创建鼠标控制对象
var controls = new THREE.OrbitControls(camera,renderer.domElement);