变换
交互式变换允许用户通过直接操作来操作元素的缩放、旋转和位置。这对于构建直观的编辑界面至关重要。
变换类型
平移
通过拖动移动元素:
import { InteractivePoint } from '@wangyaoshen/locus-interaction';
const translateHandle = new InteractivePoint({
position: [100, 100],
color: '#2196F3',
onMove: (pos) => {
// 将平移应用于目标元素
targetElement.position = pos;
},
});
旋转
通过围绕枢轴拖动控制柄来旋转元素:
const rotationHandle = new InteractivePoint({
position: [150, 100], // 旋转圆上的初始位置
constrain: circle([100, 100], 50), // 约束到围绕枢轴的圆
onMove: (pos) => {
const pivot = [100, 100];
const angle = Math.atan2(pos[1] - pivot[1], pos[0] - pivot[0]);
targetElement.rotation = angle;
},
});
缩放
通过拖动角控制柄来缩放元素:
const scaleHandle = new InteractivePoint({
position: [150, 150], // 边界框的角
onMove: (pos) => {
const center = [100, 100];
const distance = Math.sqrt(
Math.pow(pos[0] - center[0], 2) +
Math.pow(pos[1] - center[1], 2)
);
const scale = distance / 50; // 原始距离为 50
targetElement.scale = [scale, scale];
},
});
变换小部件
使用 TransformWidget 进行完整的变换控制:
import { TransformWidget } from '@wangyaoshen/locus-interaction';
const widget = new TransformWidget({
element: myElement,
showTranslate: true,
showRotate: true,
showScale: true,
onChange: (transform) => {
console.log('变换已更改:', transform);
},
});