You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React THREEJS中如何根据线条方向移动长度标签位置

解决方案

首先修正你代码里的小错误:P1.Y要改为P1.y(THREE.Vector3的属性为小写),以下是具体实现:

核心思路

要让标签沿线段垂直方向偏移,关键是计算垂直于线段的单位向量——这个向量会自动适配线条方向:

  • 水平线段的垂直方向为Y轴,标签将沿Y轴上下移动
  • 竖直线段的垂直方向为X轴,标签将沿X轴左右移动

完整代码实现

import { Text } from '@react-three/drei';
import * as THREE from 'three';

// 线段端点
const P1 = new THREE.Vector3(-300.79, -296.96, 0);
const P2 = new THREE.Vector3(101.49,  -8.43, 0);

// 1. 计算线段中点P3
const midX = (P2.x + P1.x) / 2;
const midY = (P2.y + P1.y) / 2;
const P3 = new THREE.Vector3(midX, midY, 0);

// 2. 计算线段方向向量
const dir = new THREE.Vector3().subVectors(P2, P1);

// 3. 生成垂直于线段的单位向量(顺时针方向,反向则用(dir.y, -dir.x, 0))
const perpendicularDir = new THREE.Vector3(-dir.y, dir.x, 0).normalize();

// 4. 设置偏移参数:距离(控制标签与线段的远近)、方向(1为默认,-1为反向)
const offsetDistance = 20;
const offsetDirection = 1;

// 5. 计算标签最终位置
const labelPosition = new THREE.Vector3().addVectors(
  P3,
  perpendicularDir.multiplyScalar(offsetDistance * offsetDirection)
);

// 计算线段长度(用于标签文本)
const lineLength = dir.length().toFixed(2);

// React ThreeJS中渲染标签组件
function LineLengthLabel() {
  return (
    <Text position={labelPosition} color="#000" fontSize={12}>
      {lineLength}
    </Text>
  );
}

关键细节

  • 方向切换:将offsetDirection设为-1,水平线段标签会从上方移到下方,竖直线段标签会从左侧移到右侧,完全满足你的移动需求。
  • 偏移距离:offsetDistance可根据场景尺寸调整,数值越大标签离线段越远。
  • 适配任意线段:这套逻辑不仅支持水平/竖直线,还能自动适配倾斜线段的垂直偏移需求。

内容的提问来源于stack exchange,提问作者Shoaib Ijaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:07:02