线
交互式线条允许用户通过拖动端点来操作线段。这对于演示距离、斜率和线性关系等概念很有用。
线段
具有两个可拖动端点的基本线段。拖动起点和终点以查看实时更新的线条。
import { InteractiveLine } from '@wangyaoshen/locus-interaction';
const line = new InteractiveLine({
start: [100, 200],
end: [400, 100],
color: '#4CAF50',
lineWidth: 4,
pointRadius: 14,
onChange: (start, end) => {
const length = Math.sqrt(
Math.pow(end[0] - start[0], 2) +
Math.pow(end[1] - start[1], 2)
);
console.log('长度:', length);
},
});
约束端点
您可以对单个端点应用约束,以实现更受控的交互。
import {
InteractiveLine,
horizontal,
vertical
} from '@wangyaoshen/locus-interaction';
// 起点水平移动,终点垂直移动
const line = new InteractiveLine({
start: [100, 150],
end: [300, 150],
constrainStart: horizontal(150),
constrainEnd: vertical(300),
onChange: (start, end) => {
console.log('线条已更改:', start, end);
},
});
线条属性
线条组件提供了几个计算属性:
const line = new InteractiveLine({
start: [0, 0],
end: [100, 100],
});
// 获取线条长度
const length = line.getLength(); // 141.42...
// 获取中点
const midpoint = line.getMidpoint(); // [50, 50]
// 获取斜率
const slope = line.getSlope(); // 1
// 获取以弧度为单位的角度
const angle = line.getAngle(); // 0.785... (45 度)
属性
| 名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
start | Vector2 | [0, 0] | 起点位置 |
end | Vector2 | [100, 100] | 终点位置 |
color | string | '#4CAF50' | 线条和点的颜色 |
lineWidth | number | 4 | 线条描边宽度 |
pointRadius | number | 14 | 端点半径 |
constrainStart | ConstraintFunction | - | 起点约束 |
constrainEnd | ConstraintFunction | - | 终点约束 |
onChange | (start, end) => void | - | 线条更改时的回调 |
在 Motion Canvas 2D 中使用
在 Motion Canvas 2D 中,您可以使用 InteractiveLine2D 组件:
import { InteractiveLine2D } from '@wangyaoshen/locus-2d';
<InteractiveLine2D
start={[100, 200]}
end={[400, 100]}
stroke="#4CAF50"
lineWidth={4}
pointSize={14}
onChange={(start, end) => {
const length = start.sub(end).magnitude;
console.log('长度:', length);
}}
/>