HTML中使用SVG绘制曲线并实现点击高亮效果
HTML中使用SVG绘制曲线并实现点击高亮效果下面是一个完整的HTML示例使用SVG绘制多条曲线并实现鼠标点击时高亮显示选中的曲线!DOCTYPEhtmlhtmllangzh-CNheadmetacharsetUTF-8metanameviewportcontentwidthdevice-width, initial-scale1.0titleSVG曲线点击高亮示例/titlestylebody{font-family:Arial,sans-serif;display:flex;flex-direction:column;align-items:center;padding:20px;}h1{color:#333;}.container{margin-top:20px;border:1px solid #ddd;padding:10px;border-radius:5px;background-color:#f9f9f9;}svg{border:1px solid #ccc;background-color:white;}.info{margin-top:15px;font-style:italic;color:#666;}/style/headbodyh1SVG曲线点击高亮示例/h1p点击任意一条曲线可以高亮显示它/pdivclasscontainersvgidcurveChartwidth600height400viewBox0 0 600 400!-- 定义渐变用于高亮效果 --defslinearGradientidhighlightGradientx10%y10%x2100%y20%stopoffset0%stylestop-color:#ff9900;stop-opacity:1/stopoffset100%stylestop-color:#ff3300;stop-opacity:1//linearGradient/defs!-- 背景网格线 --pathdM 50 0 V 400 M 150 0 V 400 M 250 0 V 400 M 350 0 V 400 M 450 0 V 400 M 550 0 V 400stroke#eeestroke-width1/pathdM 0 50 H 600 M 0 150 H 600 M 0 250 H 600 M 0 350 H 600stroke#eeestroke-width1/!-- 曲线1 - 蓝色 --pathidcurve1classcurvedM 50 200 C 150 50, 250 350, 350 150 C 450 350, 550 50, 550 200fillnonestroke#3498dbstroke-width3data-name曲线1: 蓝色正弦波/!-- 曲线2 - 绿色 --pathidcurve2classcurvedM 50 100 C 150 300, 250 100, 350 300 C 450 100, 550 300, 550 100fillnonestroke#2ecc71stroke-width3data-name曲线2: 绿色方波/!-- 曲线3 - 红色 --pathidcurve3classcurvedM 50 300 C 150 100, 250 300, 350 100 C 450 300, 550 100, 550 300fillnonestroke#e74c3cstroke-width3data-name曲线3: 红色三角波//svg/divdivclassinfoidcurveInfo点击一条曲线查看详细信息/divscriptdocument.addEventListener(DOMContentLoaded,function(){constcurvesdocument.querySelectorAll(.curve);constcurveInfodocument.getElementById(curveInfo);// 存储原始颜色constoriginalColors{};curves.forEach(curve{originalColors[curve.id]curve.getAttribute(stroke);});// 为每条曲线添加点击事件curves.forEach(curve{curve.addEventListener(click,function(e){// 移除之前所有曲线的高亮类curves.forEach(c{c.setAttribute(stroke,originalColors[c.id]);});// 高亮当前曲线this.setAttribute(stroke,url(#highlightGradient));this.setAttribute(stroke-width,4);// 显示曲线信息constnamethis.getAttribute(data-name);curveInfo.textContent已选择:${name};// 阻止事件冒泡到SVG元素e.stopPropagation();});});// 可选为SVG添加点击事件以取消高亮constsvgdocument.getElementById(curveChart);svg.addEventListener(click,function(){// 重置所有曲线到原始状态curves.forEach(curve{curve.setAttribute(stroke,originalColors[curve.id]);curve.setAttribute(stroke-width,3);});curveInfo.textContent点击一条曲线查看详细信息;});});/script/body/html代码说明SVG结构:创建了一个600x400的SVG画布添加了背景网格线作为参考定义了三条不同类型的曲线正弦波、方波、三角波高亮效果实现:使用SVG的linearGradient定义了一个渐变颜色为每条曲线存储了原始颜色点击曲线时重置所有曲线的颜色和宽度为当前曲线应用渐变颜色和加粗效果显示曲线信息交互功能:点击曲线会高亮显示并显示信息点击SVG空白区域会取消所有高亮样式:添加了基本的CSS样式使界面更美观曲线使用不同颜色区分自定义修改建议要添加更多曲线只需复制path元素并修改d属性定义曲线形状和颜色可以修改渐变颜色或使用纯色高亮直接设置stroke属性为固定颜色可以添加动画效果使高亮更平滑可以扩展为显示更多曲线信息或添加图例这个示例提供了完整的交互功能你可以根据需要进一步定制样式和功能。