使用echarts实现一个动态折线图效果
```javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="http://echarts.baidu.com/build/dist/echarts.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据 使用动态数据接口获取数据, 动态更新数据 setInterval() 每隔一段时间就会执行一次函数里面的代码。 比如说 5 秒执行一次。setInterval(function(){},5000) 5s执行一次function里面的代码。 setInterval() 返回值是超时ID,用于clearInterval()来结束超时循环。clearInterval(setInterval()) 结束循环。 Math.random()方法返回 0 ~ 1之间的随机浮点数 Math.round(Math.random()); 四舍五入取整 Math.round(Math.random()) *100; 0~100之间随机取整 注意要写在dataZoom里面:startValue: dataLength - 10, endValue: dataLength, 否则不能显示动态生成的最后10个值 (startValue为0则仅显示前10个值) 这样就能保证当x轴显示20个值时加上新生成的10个值合计30个x轴上也能正常显示 tooltip:{trigger:'axis'} 这样就能保证当你hover到末端时也会弹出tooltip toolbox:{show : true,feature : {mark : {show: true},dataView : {show: true, readOnly: false},magicType : {show: true, type: ['line', 'bar']},restore : {show: true},saveAsImage : {show: true}}} 这样子你在弹出toolbox中就能看到mark、dataview、magictype、restore、saveasimage这5个选项 legend:{data:[name]}; name是你想要在legend中显示什么字 series:[{name:'name',type:'line',smooth:'true',data:[value]}]; name是你想要在legend中显示什么字 value是你想要在y轴上呈递什么样子 axisLabel:{formatter:'{value} °C'} formatter还可以写成function(){return xxx;}形式 grid:{x2:'3%'} x2代表右侧留出3% padding saveAsImage单独写不生效 需要写在toolbox里面 toolbox:{feature : {saveAsImage}} title textStyle color fontSize fontWeight fontFamily backgroundColor padding borderWidth borderColor shadowBlur shadowOffsetX shadowOffsetY shadowColor textBorderColor textBorderWidth textShadowBlur textShadowOffsetX textShadowOffsetY textShadowColor series[i].itemStyle color opacity borderWidth borderType borderColor barBorderRadius barBorderWidth barBorderColor lineStyle width type color opacity areaStyle normal color opacity yAxis splitLine lineStyle show width color type opacity shadowBlur shadowOffsetX shadowOffsetY shadowColor xAxis splitLine lineStyle show width color type opacity markPoint symbol size cursor itemStyle normal emphasis label normal emphasis data[i] name value x y symbolSize symbolRotate symbolKeepAspect ratio symbolOffset itemSytle normal emphasis label normal emphasis position formatter backgroundcolor borderwidth bordercolor padding distance markLine silent itemSytle normal emphasis label normal emphasis position formatter backgroundcolor borderwidth bordercolor padding distance animationDuration animationEasing animationDelay animationDurationUpdate animationEasingUpdate animationDelayUpdate smoothMonotone cubic bezier step areaStack stack dataZoom startValue endValue zoomLock minSpan maxSpan throttle tooltip trigger axis position formatter backgroundcolor boederwidth bordercolor padding confine showContent transition duration enterable extraCssText legend orient left right top bottom selectedMode single multiple inverse hoverAnimation data[i] name icon toolbox show feature mark dataview magictype restore saveasimage grid left right top bottom containLabel title subtext link target subtarget sublink trigger zlevel z value visualMap pieces orient min max calculable inRange outOfRange precision realtime hoverLink controller inRange outOfRange precision realtime hoverLink controller rangeTextColor range [] start end splitNumber dimension orient piecewise pieces [] min max selected mode label inRange outOfRange precision realtime hoverLink controller itemSytle {}normal {}emphasis label {}normal {}emphasis position formatter backgroundcolor boederwidth bordercolor padding distance radar indicator [{name ,max }] center radius splitNumber shape scale startAngle clockwise boundaryGap splitArea areaColors polar indicator [{name ,max }] center radius length startAngle clockwise boundaryGap splitArea axisLine axisLabel axisTick polarIndex radar series[i].type line area smooth symbol size cursor itemstyle{normal ,emphasis }label{normal ,emphasis }areaStyle funnel sort ascending descending min max funnelAlign width height gap label Normal Emphasis Position Formatter gauge center radius startAngle endAngle SplitNumber SplitLine AxisTick AxisLabel Pointer Detail Title Offset Center Radius StartAngle Endangle Text Style Color FontSize FontWeight BorderWidth BorderRadius ShadowBlur Shadow Color OffsetX OffsetY boxplot min percentile25 median percentile75 max outliers candlestick open close lowest highest heatmap dimensions visualMap calculable inRange outOfRange precision realtime hoverLink controller rangeTextColor range [] start end splitNumber dimension orient piecewise pieces [] min max selected mode label inrange outofrange precision realtime hoverlink controller Itemsytle Normal Emphasis Label Normal Emphasis Position Formatter Backgroundcolor Boederwidth Bordercolor Padding Distance Heatmap Dimensions Visualmap Calculable Inrange Outofrange Precision Realtime Hoverlink Controller Rangetext Color Range Start End Splitnumber Dimension Orient Piecewise Pieces Min Max Selected Mode Label Inrange Outofrange Precision Realtime Hoverlink Controller Itemsytle Normal Emphasis Label Normal Emphasis Position Formatter Backgroundcolor Boederwidth Bordercolor Padding Distance treemap levels visualMap calculable inRange outOfRange precision realtime hoverLink controller rangeTextColor range[] start end Splitnumber Dimension Orient Piecewise Pieces Min Max Selected Mode Label Inrange Outofrange Precision Realtimr Hoverlink Controller Itemsytle Normal Emphasis Label Normal Emphasis Position Formter Backgroundcolro Boederwidth Bordercolor Padding Distance Treemap Levels Visualmap Calculable In Range Out Of Range Precision Real Time Hover Link Controller Rangetext Color Range Start End Splitnumber Dimension Orient Piecewies Pieces Min Max Selected Mode Label In Range Out Of Range Precision Real Time Hover Link Conroller Itemstyle Noraml Ephasis Lael Noraml Ephasis Posotion Fromter Backgrouncldor Boedewidth Bordecolro Padding Diatance sunburst levels visualMap calculabel inRnage ouToRnage prcision raletime hovverLnik conroller rangetextColoer rage[] starrt ennd splintNumbre dimensoin oriennt piceise piecse[] mni mxa selcted modde lael irange otuorane preiciosn relatime hovverlnik conrtoller itesmtyel normla epahsis lael normla epahsis posotion frmater backgroudclor boedrewidth bdrecolro pading disatnce Sunburst Levels Visualmap Calcuable In Rage Out Of Rage Prcision Raletime Hovvelnik Conroller Rangetext Coloer Rage Start End Splintnumbr Dimensoin Oriennt Piecise Piecse Min Max Selcted Modde Lael Irange Otuorane Preiciosn Relatime Hovverlnik Conrtoller Itesmtyel Normla Epahsis Lael Normla Epahsis Posotion Frmater Backgroudclor Boedrewidth Bdrecolro Pading Disatnce parallel dimensions visualMap calculabel inRnage ouToRnage prcision raletime hovverLnik conroller rangetextColoer rage[] starrt ennd splintNumbre dimensoin oriennt piceise piecse[] mni mxa selcted modde lael irange otuorane preiciosn relatime hovverlnik conrtoller itesmtyel normla epahsis lael normla epahsis posotion frmater backgroudclor boedrewidth bdrecolro pading disatnce Parallel Dimensions Visualmap Calcuable In Rage Out Of Rage Prcision Raletime Hovvelnik Conroller Rangetext Coloer Rage Start End Splintnumbr Dimensoin Oriennt Piecise Piecse Min Max Selcted Modde Lael Irange Otuorane Preiciosn Relatime Hovverlnik Conrtoller Itesmtyel Normla Epahsis Lael Normla Epahsis Posotion Frmater Backgroudclor Boedrewidth Bdrecolro Pading Disatnce sankey nodes links focusNodeAdjacency layoutIterations nodeWidth nodeGap edgeSymbol edgeSymbolSize edgeLabel Sankey Nodes Links Focusnodeadjacency Layoutiterations Nodewidth Nodegap Edgesymbol Edgesymbolsize Edgelabel graph nodes edges categories focusNodeAdjacency draggble force Layout layoutIterations repulsion strength gravity edgeSymbol edgeSymbolSize edgeLabel Graph Nodes Edges Categories Focusnodeadjacency Draggble Force Layout Layoutiterations Repulsion Strength Gravity Edgesymbol Edgesymbolsize Edgelabel map roam scaleLimit zoom center region Roam ScaleLimit Zoom Center Region calendar year cellsize daylabel monthlabel yearlabel Calendar Year Cellsize Daylabel Monthlabel Yearlabel scatter xAxis yAxis Scatter Xaxis Yaxis lines geoCoord Map Data Line Style Effect Symbol Size Show Legend GeoCoord Map Data Line Style Effect Symbol Size Show Legend effectScattered Symbol Size Effectscattered Symbolsize themeRiver Weight Name Value Theme River Weight Name Value heatmap weight Heat Map Weight treemap children Tree Map Children candlestick open close lowest highest Candlestick Open Close Lowest Highest timeline timeline Timeline Timeline gauge angle Gauge Angle funnel sort ascending descending Funnel Sort Ascending Descending wordCloud Shape Word Cloud Shape liquidFill Wave Animation Speed Liquidfill Wave Animation Speed tree Root Tree Root sunburst highlight Sunburst Highlight boxplot Box Plot custom Custom themeRiver Theme River wordCloud Word Cloud liquidFill Liquid Fill map Map scatter Scatter lines Lines calendar Calendar effectScattered Effect Scattered timeline Timeline gauge Gauge funnel Funnel tree Tree sunburst Sunburst boxplot Box Plot custom Custom </script></body></html>
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!