效果展示:
<div class="nowEcharts" id="nowEcharts"></div> <style > .nowEcharts { width: 100%; height: 300px; margin-bottom: 0.3rem; } </style>
1.先在data中定義option
nowOptions: { visualMap: [ { show: false, type: 'continuous', seriesIndex: 0, min: 0, max: 400, }, ], title: { left: 'left', text: '電量消耗實時統計', }, tooltip: { trigger: 'axis', formatter: function(params) { params = params[0] var date = new Date(params.name) return ( date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1] ) }, axisPointer: { animation: false, }, }, grid: { top: '15%', bottom: '10%', }, xAxis: { type: 'time', splitLine: { show: false, }, triggerEvent: true, }, yAxis: { type: 'value', boundaryGap: [0, '100%'], max: 100, splitLine: { show: false, }, }, series: [ { type: 'line', showSymbol: false, hoverAnimation: false, data: [], }, ], },
2.生成折線圖
(1)初始化數據
nowChart() { let that = this var data = [] var now = +new Date() var value = Math.random() * 1000 for (var i = 0; i < 60; i++) { now = new Date(+now + this.oneDay) data.push(this.randomData(now, value)) } // 基於准備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('nowEcharts')) // 繪制圖表 var temp = 59 let options = Object.assign(that.nowOptions, {}) options.series.forEach((item) => { item.data = data item.markPoint = { data: [ [ { symbol: 'none', x: '95%', }, { symbol: 'circle', name: '實時數據', value: data[temp].value[1], xAxis: data[temp].value[0], }, ], ], } }) myChart.setOption(options) // 1秒定時器 setInterval(() => { for (var i = 0; i < 1; i++) { data.shift() now = new Date(+now + this.oneDay) data.push(this.randomData(now, value)) } myChart.setOption(options) }, 1000) },
(2)生成隨機數
randomData(now, value) { value = Math.random() * 100 var valueName = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate() + ' ' + (now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()) + ':' + (now.getMinutes() >= 10 ? now.getMinutes() : '0' + now.getMinutes()) + ':' + (now.getSeconds() >= 10 ? now.getSeconds() : '0' + now.getSeconds()) return { name: now.toString(), value: [valueName, Math.round(value)], } },