基本 SVG 组件
首先,让我们创建一个简单的 SVG 组件,它接受宽度和高度作为 props。这将是我们图表的起点。
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}"></line> ); };
添加 Y 轴
我们将使用另一条
const drawYAxis = () => { const middleX = width / 2; return ( <line x1="{middleX}" y1="{0}" x2="{middleX}" y2="{height}" stroke="{lineColor}"></line> ); };
将坐标绘制为直线路径
折线图的关键部分是连接不同点的线。让我们绘制一些示例坐标并使用 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"></path>; };
填充线下方区域的选项
我们可以用颜色填充线下方的区域来增强图形。这可以使用附加元件来完成。考虑 prop 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"></path> ); };
跟踪光标
让我们添加一个跟随光标在图形路径上移动的圆圈。
我们需要 SVG 组件的引用来访问 SVG 元素的边界框。也是我们的跟踪圆的参考,它将用于跟踪图表上的光标。
const svgRef = useRef(); const circleRef = useRef(); // ... const drawTrackingCircle = () => { return ( <circle ref="{circleRef}" r="{6}" fill="red" style="{{" display: initially hidden></circle> ); }; // ... <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) || (p1.x >= cursorX && p2.x <p>光标移动跟踪方法。它使用 getIntersectionPoint 方法来查找当前交叉点坐标。<br> </p> <pre class="brush:php;toolbar:false">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>
LineGraph 演示的 Codesandbox 链接
Isaac Smith 在 Unsplash 上的博客照片
感谢您的阅读❤
以上是在 ReactJS 中构建您自己的交互式线图的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript字符串替换方法详解及常见问题解答 本文将探讨两种在JavaScript中替换字符串字符的方法:在JavaScript代码内部替换和在网页HTML内部替换。 在JavaScript代码内部替换字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 该方法仅替换第一个匹配项。要替换所有匹配项,需使用正则表达式并添加全局标志g: str = str.replace(/fi

本教程向您展示了如何将自定义的Google搜索API集成到您的博客或网站中,提供了比标准WordPress主题搜索功能更精致的搜索体验。 令人惊讶的是简单!您将能够将搜索限制为Y

因此,在这里,您准备好了解所有称为Ajax的东西。但是,到底是什么? AJAX一词是指用于创建动态,交互式Web内容的一系列宽松的技术。 Ajax一词,最初由Jesse J创造

本文系列在2017年中期进行了最新信息和新示例。 在此JSON示例中,我们将研究如何使用JSON格式将简单值存储在文件中。 使用键值对符号,我们可以存储任何类型的

利用轻松的网页布局:8个基本插件 jQuery大大简化了网页布局。 本文重点介绍了简化该过程的八个功能强大的JQuery插件,对于手动网站创建特别有用

核心要点 JavaScript 中的 this 通常指代“拥有”该方法的对象,但具体取决于函数的调用方式。 没有当前对象时,this 指代全局对象。在 Web 浏览器中,它由 window 表示。 调用函数时,this 保持全局对象;但调用对象构造函数或其任何方法时,this 指代对象的实例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。这些方法使用给定的 this 值和参数调用函数。 JavaScript 是一门优秀的编程语言。几年前,这句话可

jQuery是一个很棒的JavaScript框架。但是,与任何图书馆一样,有时有必要在引擎盖下发现发生了什么。也许是因为您正在追踪一个错误,或者只是对jQuery如何实现特定UI感到好奇

该帖子编写了有用的作弊表,参考指南,快速食谱以及用于Android,BlackBerry和iPhone应用程序开发的代码片段。 没有开发人员应该没有他们! 触摸手势参考指南(PDF) Desig的宝贵资源


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3汉化版
中文版,非常好用

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)