three.js学习笔记 3.点和线

66 阅读1分钟

在three.js中 点和线的呈现与常规3d对象不同 不需要网格 而是由自己独特的对象
@react-three/drei已经提供封装好的点、线组件

线

<Line
  points={[
    [0, 0, 0],
    [0, 0, 5],
  ]}
  color='blue'
  lineWidth={2}
/>


const positions = [
  [-1, 1, 0],
  [1, 1, 0],
] as const
const colors = ['#4096ff', '#ff4096']

      <Points>
        {/* vertexColors表示每个点可以自行设置颜色 */}
        <pointsMaterial vertexColors size={2} />
        {positions.map((position, index) => {
          return (
            <Point
              key={index}
              position={position}
              color={colors[index]}
            ></Point>
          )
        })}
      </Points>

image.png

也可以不生成组件 直接通过配置生成点

import { Color } from 'three'

const positionBuffer = new Float32Array(positions.flat())
const colorBuffer = new Float32Array(
  colors
    .map((color) => {
    // 这里必须使用three.js的Color把rgb颜色转化到线性空间 不然会变浅
      return new Color(color).toArray()
    })
    .flat(),
)
      <Points positions={positionBuffer} colors={colorBuffer}>
        <pointsMaterial vertexColors size={2} />
      </Points>

pointsMaterial可以去除vertexColors属性 改为color属性统一设置颜色

<pointsMaterial color={'#4096ff'} size={2} />

点云

由于点只能被渲染为正方形 因此不会单独使用 而是使用大量点形成点云

const positions: number[][] = new Array(1000).fill(null).map((_, index) => {
  return new Array(3)
    .fill(null)
    .map(() => ((Math.random() - 0.5) * index) / 100)
})
const positionBuffer = new Float32Array(positions.flat())

export default function PointsAndLines() {
  return (
    <Canvas>
      <Axes />
      <OrbitControls />
      <Points positions={positionBuffer}>
        <pointsMaterial color={'#4096ff'} size={0.05} />
      </Points>
    </Canvas>
  )
}

image.png