完成 手柄和放盘盘控制的时候 辅助线的绘制

This commit is contained in:
mmc
2026-10-16 10:17:58 +08:00
parent fe0847ac35
commit 236023733e
2 changed files with 161 additions and 121 deletions

View File

@@ -1,132 +1,200 @@
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef, useState } from 'react';
type GuideLineProps = { type GuideLineProps = {
/** 方向 forward前进 reverse倒车 */ /** 方向 forward前进 reverse倒车 */
direction: 'forward' | 'reverse'; direction: 'forward' | 'reverse';
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */ /** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
steer: number; steer: number;
/** 画布宽度 */ /** 引导线底部(车尾端)两条线间距,默认为容器宽度的 40% */
width?: number;
/** 画布高度 */
height?: number;
/** 引导线底部(车尾端)两条线间距 */
bottomGap?: number; bottomGap?: number;
/** 引导线顶部(远端)两条线间距 */ /** 引导线顶部(远端)两条线间距,默认为容器宽度的 20% */
topGap?: number; topGap?: number;
/** 是否显示辅助线 */
visible?: boolean;
}; };
const CarReverseGuideLine: React.FC<GuideLineProps> = ({ const CarReverseGuideLine: React.FC<GuideLineProps> = ({
direction, direction,
steer, steer,
width = 640, bottomGap,
height = 480, topGap,
bottomGap = 100, visible = true,
topGap = 160,
}) => { }) => {
const canvasRef = useRef<HTMLCanvasElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
// 监听容器大小变化
useEffect(() => {
if (!containerRef.current) return;
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { width, height } = entry.contentRect;
setSize({ width, height });
}
});
resizeObserver.observe(containerRef.current);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => { useEffect(() => {
const canvas = canvasRef.current; const canvas = canvasRef.current;
if (!canvas) return; if (!canvas || size.width === 0 || size.height === 0 || !visible) return;
const ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
if (!ctx) return; if (!ctx) return;
const { width, height } = size;
ctx.clearRect(0, 0, width, height); ctx.clearRect(0, 0, width, height);
// 车尾中心点(画布底部)
const baseX = width / 2; // 基础参数计算
const baseY = height - 20; // 前向视角:下面宽(近处),上面窄(远处)
const totalDist = direction === 'reverse' ? height * 0.82 : height * 0.68; // 后向视角:上面宽(远处固定点),下面窄(近处转弯点)
let bGap = bottomGap || (direction === 'reverse' ? width * 0.25 : width * 0.45);
let tGap = topGap || (direction === 'reverse' ? width * 0.45 : width * 0.25);
const maxWheelAngle = 45; const maxWheelAngle = 45;
// 限制车轮转角范围
const wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180; const wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180;
const step = 2; // 步长,越小曲线越平滑 const step = 2;
// 迭代计算轨迹点函数 // 迭代计算轨迹点函数
const getPathPoints = (side: 'left' | 'right'): [number, number][] => { const getPathPoints = (side: 'left' | 'right'): [number, number][] => {
const points: [number, number][] = []; const points: [number, number][] = [];
let x = baseX; const totalDist = direction === 'reverse' ? height * 0.75 : height * 0.7;
let y = baseY;
let angle = -Math.PI / 2; // 初始朝向:向上(画布Y减小方向)
const stepCount = Math.floor(totalDist / step); const stepCount = Math.floor(totalDist / step);
points.push([x, y]);
for (let i = 0; i < stepCount; i++) { if (direction === 'forward') {
// 当前进度 0~1,0=底部起点,1=最远顶部 // 前视角:底部固定,向上延伸并转向
let x = width / 2;
let y = height - 20;
let angle = -Math.PI / 2;
for (let i = 0; i <= stepCount; i++) {
const progress = i / stepCount; const progress = i / stepCount;
// 线性插值:从底部gap过渡到顶部gap const currentGap = bGap * (1 - progress) + tGap * progress;
const currentGap = bottomGap * (1 - progress) + topGap * progress;
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2; const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
if (Math.abs(wheelAngleRad) < 0.001) { if (Math.abs(wheelAngleRad) > 0.001) {
// 回正:直线向上 // 恢复前视转向灵敏度:使用固定曲率
y -= step; const curvature = height * 0.5;
} else { const turnStepRad = (step * Math.tan(wheelAngleRad)) / curvature;
// 有转向:改变朝向,再前进一小步
const turnStepRad = step * Math.tan(wheelAngleRad) / 240;
// 分母240:控制转弯曲率,调大转弯更平缓;调小弯更急
angle += turnStepRad; angle += turnStepRad;
x += Math.cos(angle) * step; x += Math.cos(angle) * step;
y += Math.sin(angle) * step; y += Math.sin(angle) * step;
} else {
y -= step;
} }
// 叠加当前侧边偏移 points.push([x + sideOffset, y]);
const px = x + sideOffset; if (y < 0) break;
const py = y;
points.push([px, py]);
// 超出画布提前停止绘制
if (py < 0 || px < 0 || px > width) break;
} }
} else {
// 后视角:顶部固定点,向下延伸至底部并随转向摆动
// 我们从顶部 (width/2, height - totalDist) 开始向下画
let x = width / 2;
let startY = height - totalDist - 20;
let y = startY;
let angle = Math.PI / 2; // 向下
for (let i = 0; i <= stepCount; i++) {
const progress = i / stepCount; // 0 是顶部,1 是底部
// 后视角透视:progress=0(顶部)时使用 tGap,progress=1(底部)时使用 bGap
const currentGap = tGap * (1 - progress) + bGap * progress;
const sideOffset = side === 'left' ? currentGap / 2 : -currentGap / 2;
if (Math.abs(wheelAngleRad) > 0.001) {
// 转向逻辑:从顶部向下走,底部随 steer 摆动
// steer 为负(左打)时,底部应该向左摆动(x减小)
const curvature = height * 0.5; // 与前视角保持一致的曲率灵敏度
const turnStepRad = (step * Math.tan(wheelAngleRad)) / curvature;
angle -= turnStepRad; // 后视角向下绘制,减去增量以实现正确的左右转向
x += Math.cos(angle) * step;
y += Math.sin(angle) * step;
} else {
y += step;
}
points.push([x + sideOffset, y]);
}
// 后视角的点是从上往下的,为了统一绘制逻辑(从下往上渐变),我们翻转数组
points.reverse();
}
return points; return points;
}; };
// 绘制左右两条轨迹 // 绘制左右两条轨迹
ctx.lineWidth = 3;
ctx.strokeStyle = '#0f0';
ctx.setLineDash([]);
const leftPath = getPathPoints('left'); const leftPath = getPathPoints('left');
const rightPath = getPathPoints('right'); const rightPath = getPathPoints('right');
const drawPath = (pts: [number, number][]) => {
const drawPath = (pts: [number, number][], color: string, dash: number[] = []) => {
if (pts.length < 2) return;
ctx.beginPath(); ctx.beginPath();
pts.forEach(([px, py], idx) => { ctx.lineWidth = 4;
if (idx === 0) ctx.moveTo(px, py); ctx.strokeStyle = color;
else ctx.lineTo(px, py); ctx.setLineDash(dash);
}); ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.moveTo(pts[0][0], pts[0][1]);
for (let i = 1; i < pts.length; i++) {
ctx.lineTo(pts[i][0], pts[i][1]);
}
ctx.stroke(); ctx.stroke();
ctx.beginPath(); // 强制清空当前路径缓存!重点!
}; };
drawPath(leftPath);
drawPath(rightPath); // 渐变色绘制
const gradient = ctx.createLinearGradient(0, height, 0, 0);
gradient.addColorStop(0, 'rgba(0, 255, 0, 0.8)'); // 近处绿色
gradient.addColorStop(0.5, 'rgba(255, 255, 0, 0.8)'); // 中间黄色
gradient.addColorStop(1, 'rgba(255, 0, 0, 0.8)'); // 远处红色
drawPath(leftPath, gradient);
drawPath(rightPath, gradient);
// ========== 横向距离标记虚线 ========== // ========== 横向距离标记虚线 ==========
ctx.strokeStyle = '#ff0';
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.setLineDash([8, 6]); ctx.setLineDash([10, 8]);
const markCount = 3; const markCount = 4;
for (let m = 1; m <= markCount; m++) { for (let m = 1; m <= markCount; m++) {
const ratio = m / (markCount + 1); const ratio = m / (markCount + 1);
const idx = Math.floor(leftPath.length * ratio); const idx = Math.floor(leftPath.length * ratio);
if (idx >= leftPath.length) continue; if (idx >= leftPath.length || idx >= rightPath.length) continue;
const [lx, ly] = leftPath[idx]; const [lx, ly] = leftPath[idx];
const [rx, ry] = rightPath[idx]; const [rx, ry] = rightPath[idx];
// 根据距离改变颜色
ctx.strokeStyle = ratio < 0.3 ? 'rgba(0, 255, 0, 0.6)' :
ratio < 0.7 ? 'rgba(255, 255, 0, 0.6)' : 'rgba(255, 0, 0, 0.6)';
ctx.beginPath(); ctx.beginPath();
ctx.moveTo(lx, ly); ctx.moveTo(lx, ly);
ctx.lineTo(rx, ry); ctx.lineTo(rx, ry);
ctx.stroke(); ctx.stroke();
} }
// ========== 车身底部框 ========== }, [direction, steer, size, bottomGap, topGap, visible]);
//ctx.setLineDash([]);
//ctx.strokeStyle = '#0ff';
//ctx.lineWidth = 2;
//ctx.beginPath();
//ctx.rect(baseX - bottomGap / 2, baseY - 30, bottomGap, 30);
//ctx.stroke();
}, [direction, steer, width, height, bottomGap, topGap]);
return ( return (
<div style={{ position: 'relative', width, height }}> <div
{/* 背景倒车画面,可以替换 video / img */} ref={containerRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
pointerEvents: 'none',
zIndex: 5,
display: visible ? 'block' : 'none'
}}
>
<canvas <canvas
ref={canvasRef} ref={canvasRef}
width={width} width={size.width}
height={height} height={size.height}
style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} style={{ width: '100%', height: '100%' }}
/> />
</div> </div>
); );
}; };
export default CarReverseGuideLine; export default CarReverseGuideLine;

View File

@@ -96,10 +96,6 @@ export default function DeviceStatusPage() {
const hasRequestedControlRef = useRef(false); const hasRequestedControlRef = useRef(false);
const [messageApi, contextHolder] = message.useMessage(); const [messageApi, contextHolder] = message.useMessage();
const [direction, setDirection] = useState<'forward' | 'reverse'>('reverse');
const [steer, setSteer] = useState(0);
// 视频播放开关 // 视频播放开关
const [isVideoPlaying, setIsVideoPlaying] = useState(false); const [isVideoPlaying, setIsVideoPlaying] = useState(false);
@@ -673,17 +669,17 @@ export default function DeviceStatusPage() {
const handleGamepadUpdate = useCallback((state) => { const handleGamepadUpdate = useCallback((state) => {
console.log('handleGamepadUpdate called with state:', isControlled); console.log('handleGamepadUpdate called with state:', isControlled);
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏) // 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
if (!isControlled) { //if (!isControlled) {
if (!hasRequestedControlRef.current && !connecting) { // //if (!hasRequestedControlRef.current && !connecting) {
hasRequestedControlRef.current = true; // // hasRequestedControlRef.current = true;
handleControlModal(); // // handleControlModal();
} // //}
return; // return;
} //}
console.log('Gamepad state updated:', state); console.log('Gamepad state updated:', state);
// 记录方向盘 xy 坐标,用于倒车影像叠加层 // 记录方向盘 xy 坐标,用于倒车影像叠加层
if (state?.axes) { if (state?.axes) {
setSteerXY({ x: state.axes[0] || 0, y: state.axes[1] || 0 }); setSteerXY({ x: state.axes[2] || 0, y: state.axes[1] || 0 });
} }
controllerRef.current?.sendGamepad(state); controllerRef.current?.sendGamepad(state);
}, [isControlled, connecting]); }, [isControlled, connecting]);
@@ -974,32 +970,6 @@ export default function DeviceStatusPage() {
</div> </div>
{/*<div style={{ marginBottom: 16 }}>
<button onClick={() => setDirection('reverse')} style={{ marginRight: 8 }}>倒车</button>
<button onClick={() => setDirection('forward')}>前进</button>
<div style={{ marginTop: 8 }}>
方向盘转角:{steer}°
<br />
<input
type="range"
min={-45}
max={45}
value={steer}
onChange={(e) => setSteer(Number(e.target.value))}
/>
<p>左滑:左转(负数)|右滑:右转(正数)</p>
</div>
</div>
<CarReverseGuideLine
direction="reverse"
steer={steer}
width={640}
height={480}
bottomGap={280} // 车尾端两条线间距
topGap={100} // 远端顶部两条线间距
/>*/}
<div style={{ padding: 0 }}> <div style={{ padding: 0 }}>
{contextHolder} {contextHolder}
@@ -1347,7 +1317,11 @@ export default function DeviceStatusPage() {
<div style={{ position: 'relative', width: '100%', height: '100%' }}> <div style={{ position: 'relative', width: '100%', height: '100%' }}>
{/*<AgrtcRoomRobot CHANNEL={device?.serialNumber || ''} />*/} {/*<AgrtcRoomRobot CHANNEL={device?.serialNumber || ''} />*/}
<AgrtcRoomRobot CHANNEL={"41-thream03"} /> <AgrtcRoomRobot CHANNEL={"41-thream03"} />
<CarReverseGuideLine
direction="forward"
steer={steerXY.x * 45}
visible={isVideoPlaying}
/>
</div> </div>
) : ( ) : (
<div style={{ position: 'relative', width: '100%', height: '100%' }}> <div style={{ position: 'relative', width: '100%', height: '100%' }}>
@@ -1363,19 +1337,17 @@ export default function DeviceStatusPage() {
error={error} error={error}
ready={ready} ready={ready}
/> />
{mowerView === 'back' && (
<CarReverseGuideLine
direction="reverse"
steer={steerXY.x * 45}
visible={isVideoPlaying}
/>
)}
</div> </div>
) )
)} )}
{/* 倒车影像叠加层:根据方向盘 xy 显示转向辅助线 */}
{/*{isVideoPlaying && (*/}
{/*<CarReverseGuideLine direction={direction} steer={steer} />*/}
{/*<ReverseCameraOverlay x={steerXY.x} y={steerXY.y} visible={true} />*/}
{/*//)}*/}
{/* 视频未加载 / 停止播放的占位 */}
{!isVideoPlaying && ( {!isVideoPlaying && (
<div style={{ <div style={{
width: '100%', height: '100%', width: '100%', height: '100%',
@@ -1532,7 +1504,7 @@ export default function DeviceStatusPage() {
{/* 权限状态标签 */} {/* 权限状态标签 */}
<Tag <Tag
icon={connecting ? <LoadingOutlined /> : (isControlled ? <UnlockOutlined /> : <LockOutlined />)} icon={connecting ? <LoadingOutlined /> : (isControlled ? <UnlockOutlined /> : <LockOutlined />)}
color={connecting ? 'gold' : (isControlled ? 'green' : 'default')} color={connecting ? 'gold' : (isControlled ? 'green' : 'red')}
style={{ margin: 0, fontSize: 12 }} style={{ margin: 0, fontSize: 12 }}
> >
{connecting {connecting