threejs 笔记 09 —— 玩一玩 ‘线’

3,189 阅读2分钟

Line

直线
  var material = new THREE.LineBasicMaterial({
    color: 0xff00ff,
    linewidth: 1,
  });

  var points = [];
  points.push(new THREE.Vector3(50, 50, 0));
  points.push(new THREE.Vector3(0, 50, 50));

  var geometry = new THREE.BufferGeometry().setFromPoints(points);

  var line = new THREE.Line(geometry, material);
  scene.add(line);
  • linewidth 控制线宽。默认值为 1。

    由于OpenGL Core Profile与 大多数平台上WebGL渲染器的限制,无论如何设置该值,线宽始终为1。

这里设置线宽,是没有效果的,官网案例提供其他的宽线的处理方式,下文写出

虚线
// 基础线条材质
      var material = new THREE.LineDashedMaterial({
        color: 0xff00ff,
        scale: 1,
        dashSize: 3,
        gapSize: 1,
      });

      var points = [];
      points.push(new THREE.Vector3(50, 50, 0));
      points.push(new THREE.Vector3(0, 50, 50));

      var geometry = new THREE.BufferGeometry().setFromPoints(points);
      var line = new THREE.Line(geometry, material);
      line.computeLineDistances(); // 计算LineDashedMaterial所需的距离的值的数组。 对于几何体中的每一个顶点,这个方法计算出了当前点到线的起始点的累积长度。
      scene.add(line);

可以调整宽度的线条
let points = [];
points.push(0, 0, 0);
points.push(0, 0, 20);

var geometry = new LineGeometry();
geometry.setPositions(points);

//类型数组创建顶点颜色color数据
var colors = []
colors.push(1,0,1)
colors.push(1,1,0)
// 设置几何体attributes属性的颜色color属性
geometry.setColors(colors); 


matLine = new LineMaterial({
	linewidth: 5, // 可以调整线宽
	vertexColors: true, // 是否使用顶点颜色
});

line = new Line2(geometry, matLine);
scene.add(line);

Line2 这个官网没有具体的api,具体参数需要通过观察源码进行探索

import { Line2 } from "./jsm/lines/Line2.js";

LineMaterial 材质

import { LineMaterial } from "./jsm/lines/LineMaterial.js";

LineGeometry 几何体对象

import { LineGeometry } from "./jsm/lines/LineGeometry.js";

设置顶点:setPositions
设置顶点颜色:setColors
以线段为基础绘制: fromLine
fromLine
var Linematerial = new THREE.LineDashedMaterial({
	color: 0xff00ff,
	scale: 1,
	dashSize: 3,
	gapSize: 1,
});

var Linegeometry = new THREE.BufferGeometry(); //声明一个缓冲几何体对象

//类型数组创建顶点位置position数据
var vertices = new Float32Array([
	10, 0, 0, //顶点1坐标
	0, 0, 0, //顶点2坐标
	10, 10, 0 //顶点3坐标
]);
// 创建属性缓冲区对象
var attribue = new THREE.BufferAttribute(vertices, 3); //3个为一组,作为一个顶点的xyz坐标
// 需要传position信息 
Linegeometry.position = attribue;

var line1 = new THREE.Line(Linegeometry, Linematerial);

var geometry = new LineGeometry();
geometry.fromLine(line1)
matLine = new LineMaterial({
	color: 0xffffff,
	linewidth: 5, // in pixels
	vertexColors: false,
	dashed: true,
});

line = new Line2(geometry, matLine);
scene.add(line);

可以自己成长的线