웹 프론트엔드 JS 튜토리얼 ReactJS에서 나만의 대화형 선 그래프 만들기

ReactJS에서 나만의 대화형 선 그래프 만들기

Oct 31, 2024 pm 06:14 PM

Building your own Interactive Line Graph in 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축 추가

다른 을 사용하겠습니다. 그래프 중앙을 수직으로 통과하는 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

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

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

JavaScript로 문자열 문자를 교체하십시오 JavaScript로 문자열 문자를 교체하십시오 Mar 11, 2025 am 12:07 AM

JavaScript로 문자열 문자를 교체하십시오

jQuery 날짜가 유효한지 확인하십시오 jQuery 날짜가 유효한지 확인하십시오 Mar 01, 2025 am 08:51 AM

jQuery 날짜가 유효한지 확인하십시오

jQuery는 요소 패딩/마진을 얻습니다 jQuery는 요소 패딩/마진을 얻습니다 Mar 01, 2025 am 08:53 AM

jQuery는 요소 패딩/마진을 얻습니다

10 JQuery Accordions 탭 10 JQuery Accordions 탭 Mar 01, 2025 am 01:34 AM

10 JQuery Accordions 탭

10 JQuery 플러그인을 확인할 가치가 있습니다 10 JQuery 플러그인을 확인할 가치가 있습니다 Mar 01, 2025 am 01:29 AM

10 JQuery 플러그인을 확인할 가치가 있습니다

노드 및 HTTP 콘솔로 HTTP 디버깅 노드 및 HTTP 콘솔로 HTTP 디버깅 Mar 01, 2025 am 01:37 AM

노드 및 HTTP 콘솔로 HTTP 디버깅

사용자 정의 Google 검색 API 설정 자습서 사용자 정의 Google 검색 API 설정 자습서 Mar 04, 2025 am 01:06 AM

사용자 정의 Google 검색 API 설정 자습서

jQuery div에 스크롤 바를 추가합니다 jQuery div에 스크롤 바를 추가합니다 Mar 01, 2025 am 01:30 AM

jQuery div에 스크롤 바를 추가합니다

See all articles