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

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 = {
/** 方向 forward前进 reverse倒车 */
direction: 'forward' | 'reverse';
/** 方向盘转角,单位°:左转负数,右转正数,范围建议 -45 ~ 45 */
steer: number;
/** 画布宽度 */
width?: number;
/** 画布高度 */
height?: number;
/** 引导线底部(车尾端)两条线间距 */
/** 引导线底部(车尾端)两条线间距,默认为容器宽度的 40% */
bottomGap?: number;
/** 引导线顶部(远端)两条线间距 */
/** 引导线顶部(远端)两条线间距,默认为容器宽度的 20% */
topGap?: number;
/** 是否显示辅助线 */
visible?: boolean;
};
const CarReverseGuideLine: React.FC<GuideLineProps> = ({
direction,
steer,
width = 640,
height = 480,
bottomGap = 100,
topGap = 160,
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) return;
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);
// 车尾中心点(画布底部)
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 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 points: [number, number][] = [];
let x = baseX;
let y = baseY;
let angle = -Math.PI / 2; // 初始朝向:向上(画布Y减小方向)
const totalDist = direction === 'reverse' ? height * 0.75 : height * 0.7;
const stepCount = Math.floor(totalDist / step);
points.push([x, y]);
for (let i = 0; i < stepCount; i++) {
// 当前进度 0~1,0=底部起点,1=最远顶部
const progress = i / stepCount;
// 线性插值:从底部gap过渡到顶部gap
const currentGap = bottomGap * (1 - progress) + topGap * progress;
const sideOffset = side === 'left' ? -currentGap / 2 : currentGap / 2;
if (Math.abs(wheelAngleRad) < 0.001) {
// 回正:直线向上
y -= step;
} else {
// 有转向:改变朝向,再前进一小步
const turnStepRad = step * Math.tan(wheelAngleRad) / 240;
// 分母240:控制转弯曲率,调大转弯更平缓;调小弯更急
angle += turnStepRad;
x += Math.cos(angle) * step;
y += Math.sin(angle) * 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;
}
// 叠加当前侧边偏移
const px = x + sideOffset;
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;
};
// 绘制左右两条轨迹
ctx.lineWidth = 3;
ctx.strokeStyle = '#0f0';
ctx.setLineDash([]);
const leftPath = getPathPoints('left');
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();
pts.forEach(([px, py], idx) => {
if (idx === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
});
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();
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.setLineDash([8, 6]);
const markCount = 3;
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) continue;
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();
}
// ========== 车身底部框 ==========
//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]);
}, [direction, steer, size, bottomGap, topGap, visible]);
return (
<div style={{ position: 'relative', width, height }}>
{/* 背景倒车画面,可以替换 video / img */}
<div
ref={containerRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
pointerEvents: 'none',
zIndex: 5,
display: visible ? 'block' : 'none'
}}
>
<canvas
ref={canvasRef}
width={width}
height={height}
style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}
width={size.width}
height={size.height}
style={{ width: '100%', height: '100%' }}
/>
</div>
);
};
export default CarReverseGuideLine;