项目中客户有这个需求(主要想看涨跌),这里记录一下。效果图 :
简单的k线图需要四条数据(//开盘(open),收盘(close),最低(lowest),最高(highest))。开盘价取折线图的实时价,收盘价也取折线图的实时价,最低最高在随机取值就会有折线图的感觉(没有中间的块,只判断涨跌)。
折线图数据实时刷新,涨跌echarts会判断(开盘价和收盘价一样,后一条数据的值比前一条数据的值大,判为涨,否则为跌)
主要代码:
getLine() { let echart = document.getElementById("goldEchart"); this.goldEchart = echarts.init(echart); let dateList = []; let valueList = []; let data = [] let dates = [] //this.lineList 后台数据格式如下: //id: 9031 //latestpri: "1510.64" //limit: "-0.16%" //time: "2019-11-01 19:20:24" //dat是一个时期格式化函数 this.lineList.forEach((value, key) => { valueList.push(Number(value.latestpri)) dates.push(dat(new Date(value.time), 'hh:mm')) let minpri = Number(value.latestpri) - Math.random() * 0.05 let maxpri = Number(value.latestpri) + Math.random() * 0.05 data.push([value.latestpri, value.latestpri, Number(minpri).toFixed(2), Number(maxpri).toFixed(2)]) }) //价格最小值(y轴最小刻度) let min = Math.round(Math.min.apply(Math, valueList)); let max = Math.round(Math.max.apply(Math, valueList)); let option = { animation: false, tooltip: { trigger: "axis", type: 'none', //提示框背景色 backgroundColor: '#DA5151', //提示框样式 formatter: function(params) { params = params[0]; return params.name + '</br><p style="background:#fff;display:inline-block;width:9px;height:9px;border-radius:50%"></p> ' + params.value[1] + '<span style="font-size:12px">' + ' ' + '</span>'; }, axisPointer: { type: 'none', //去掉提示框竖线 } }, xAxis: [{ splitNumber: 5, type: 'category', boundaryGap: false, axisLine: { show: false, onZero: false, lineStyle: { color: '#999' } }, axisLabel: { interval: 'auto', //横坐标间隔 }, axisTick: { //x轴刻度线 show: false }, data: dates }], yAxis: [{ splitNumber: 5, type: 'value', max: max + 0.5, min: min - 0.5, axisLabel: { formatter: function(value, index) { return value.toFixed(2); } }, axisLine: { show: false, //隐藏纵轴坐标线 onZero: false, lineStyle: { color: '#999' } }, axisTick: { //y轴刻度线 show: false }, splitLine: { show: true, lineStyle: { color: '#555', type: 'dotted' } }, }], grid: [{ top: 20, left: 55, right: 15, bottom: 30, }], series: [{ type: 'candlestick', name: '日K', data: data, itemStyle: { normal: { color: '#d52c21', color0: '#5ab13e', borderColor: '#d52c21', borderColor0: '#5ab13e' }, }, }] }; if(this.goldEchart) { this.goldEchart.clear() //clear 重新绘制 this.goldEchart.setOption(option); } //显示提示框 this.goldEchart.dispatchAction({ type: 'showTip', seriesIndex: 0, // 显示第几个series dataIndex: data.length - 1 // 显示第几个数据 }); }
