Files
web-Iot/src/components/devices/CarReverseGuideLine.tsx

201 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useEffect, useRef, useState } from 'react';
type GuideLineProps = {
/** 方向 forward前进 reverse倒车 */
direction: 'forward' | 'reverse';
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
steer: number;
/** 引导线底部(车尾端)两条线间距,默认为容器宽度的 40% */
bottomGap?: number;
/** 引导线顶部(远端)两条线间距,默认为容器宽度的 20% */
topGap?: number;
/** 是否显示辅助线 */
visible?: boolean;
};
const CarReverseGuideLine: React.FC<GuideLineProps> = ({
direction,
steer,
bottomGap,
topGap,
visible = true,
}) => {
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(() => {
const canvas = canvasRef.current;
if (!canvas || size.width === 0 || size.height === 0 || !visible) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const { width, height } = size;
ctx.clearRect(0, 0, width, height);
// 基础参数计算
// 前向视角:下面宽(近处),上面窄(远处)
// 后向视角:上面宽(远处固定点),下面窄(近处转弯点)
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 wheelAngleRad = Math.max(-maxWheelAngle, Math.min(maxWheelAngle, steer)) * Math.PI / 180;
const step = 2;
// 迭代计算轨迹点函数
const getPathPoints = (side: 'left' | 'right'): [number, number][] => {
const points: [number, number][] = [];
const totalDist = direction === 'reverse' ? height * 0.75 : height * 0.7;
const stepCount = Math.floor(totalDist / step);
if (direction === 'forward') {
// 前视角:底部固定,向上延伸并转向
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 currentGap = bGap * (1 - progress) + tGap * progress;
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
if (Math.abs(wheelAngleRad) > 0.001) {
// 恢复前视转向灵敏度:使用固定曲率
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]);
if (y < 0) 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;
};
// 绘制左右两条轨迹
const leftPath = getPathPoints('left');
const rightPath = getPathPoints('right');
const drawPath = (pts: [number, number][], color: string, dash: number[] = []) => {
if (pts.length < 2) return;
ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle = color;
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();
};
// 渐变色绘制
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.lineWidth = 2;
ctx.setLineDash([10, 8]);
const markCount = 4;
for (let m = 1; m <= markCount; m++) {
const ratio = m / (markCount + 1);
const idx = Math.floor(leftPath.length * ratio);
if (idx >= leftPath.length || idx >= rightPath.length) continue;
const [lx, ly] = leftPath[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.moveTo(lx, ly);
ctx.lineTo(rx, ry);
ctx.stroke();
}
}, [direction, steer, size, bottomGap, topGap, visible]);
return (
<div
ref={containerRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
pointerEvents: 'none',
zIndex: 5,
display: visible ? 'block' : 'none'
}}
>
<canvas
ref={canvasRef}
width={size.width}
height={size.height}
style={{ width: '100%', height: '100%' }}
/>
</div>
);
};
export default CarReverseGuideLine;