ReactJS에서 나만의 대화형 선 그래프 만들기
기본 SVG 구성 요소
먼저 너비와 높이를 소품으로 허용하는 간단한 SVG 구성 요소를 만들어 보겠습니다. 이것이 그래프의 출발점이 될 것입니다.
import React from "react"; const LineGraph = ({ height, width }) => { return <svg height={height} width={width}></svg>; }; export default LineGraph;
X축 추가
이제 그래프를 가로로 가로지르는 X축을 추가해 보겠습니다. 우리는
const drawXAxis = () => { const middleY = height / 2; return ( <line x1={0} y1={middleY} x2={width} y2={middleY} stroke={lineColor} /> ); };
Y축 추가
다른
const drawYAxis = () => { const middleX = width / 2; return ( <line x1={middleX} y1={0} x2={middleX} y2={height} stroke={lineColor} /> ); };
좌표를 선 경로로 그리기
선 그래프의 핵심 부분은 서로 다른 점을 연결하는 선입니다. 몇 가지 샘플 좌표를 플롯하고 SVG를 사용하여 연결해 보겠습니다.
const drawPath = () => { const pathData = coordinates .map((coordinate, index) => index === 0 ? `M ${coordinate.x} ${coordinate.y}` : `L ${coordinate.x} ${coordinate.y}` ) .join(" "); return <path d={pathData} stroke={pathColor} fill="none" />; };
선 아래 영역을 채우는 옵션
선 아래 영역을 색상으로 채워 그래프를 향상시킬 수 있습니다. 이는 추가 요소를 사용하여 수행할 수 있습니다. 이 영역을 표시하거나 숨기려면 isFillArea 소품을 고려하세요.
const drawPath = () => { const pathData = coordinates .map((coordinate, index) => index === 0 ? `M ${coordinate.x} ${coordinate.y}` : `L ${coordinate.x} ${coordinate.y}` ) .join(" "); const middleY = height / 2; const svgPath = showFillArea ? `${pathData} L ${width} ${middleY} L 0 ${middleY} Z` : pathData; const fillColor = showFillArea ? areaColor : "none"; return ( <path d={svgPath} fill={fillColor} stroke={pathColor} opacity="0.5" /> ); };
커서 추적
그래프 경로에서 커서의 움직임을 따라가는 원을 추가해 보겠습니다.
SVG 요소의 경계 상자에 액세스하려면 SVG 구성 요소에 대한 참조가 필요합니다. 또한 그래프 위에서 커서를 추적하는 데 사용되는 추적 원에 대한 참조입니다.
const svgRef = useRef(); const circleRef = useRef(); // ... const drawTrackingCircle = () => { return ( <circle ref={circleRef} r={6} fill="red" style={{ display: "none" }} // Initially hidden /> ); }; // ... <svg ref={svgRef} width={width} height={height}> // ... </svg>
그런 다음 SVG 요소에 이벤트 리스너를 추가해야 합니다. 그러면 그래프 위의 모든 커서 움직임을 듣게 됩니다.
useEffect(() => { const svgElement = svgRef.current; svgElement.addEventListener("mousemove", handleMouseMove); // clean up return () => svgElement.removeEventListener("mousemove", handleMouseMove); }, []);
다음으로 커서 위치와 경로 사이의 교차 좌표를 찾는 방법이 필요합니다.
const getIntersectionPoint = (cursorX) => { // Find the segment (p1, p2) where cursorX lies between two consecutive coordinates. const segment = coordinates.find((p1, i) => { // Get the next point const p2 = coordinates[i + 1]; // Check if cursorX falls between the two coordinates horizontally. return ( p2 && ((p1.x <= cursorX && p2.x >= cursorX) || (p1.x >= cursorX && p2.x <= cursorX)) ); }); // Return null if no valid segment is found. if (!segment) return null; // Destructure the two coordinates in the segment. const [p1, p2] = [segment, coordinates[coordinates.indexOf(segment) + 1]]; // Calculate 't' to determine the relative position between p1 and p2. const t = (cursorX - p1.x) / (p2.x - p1.x); // Interpolate the Y-coordinate using 't'. const y = p1.y + t * (p2.y - p1.y); return { x: cursorX, y }; };
커서 이동 추적 방법. getIntersectionPoint 메소드를 사용하여 현재 교차점 좌표를 찾습니다.
const handleMouseMove = (event) => { // Get SVG position const svgRect = svgRef.current.getBoundingClientRect(); // Calculate cursor's X within the SVG const cursorX = event.clientX - svgRect.left; // Find the intersection point const intersectionPoint = getIntersectionPoint(cursorX); if (intersectionPoint) { // Move the intersection circle to the calculated point circleRef.current.setAttribute("cx", intersectionPoint.x); circleRef.current.setAttribute("cy", intersectionPoint.y); circleRef.current.style.display = "block"; } };
마지막으로 이것이 그래프 구성 요소의 구조입니다
return ( <svg ref={svgRef} height={height} width={width}> {drawPath()} {drawXAxis()} {drawYAxis()} {drawTrackingCircle()} {drawDataPointCircles()} </svg> );
그래프 구성요소를 사용하는 방법
<LineGraph width={300} height={400} coordinates={samplePoints} lineColor="#000" pathColor="#00008B" areaColor="#ADD8E6" dataPointColor="#008000" showFillArea showDataPointCircle />
LineGraph 데모용 Codesandbox 링크
Unsplash에 있는 Isaac Smith의 블로그 사진
읽어주셔서 감사합니다 ❤
위 내용은 ReactJS에서 나만의 대화형 선 그래프 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









