目標效果圖:
相關代碼:
const _historyEventList = [ { time: '1921年7月23日', event: '黨的成立', }, { time: '1949年10月1日', event: '新中國成立', }, { time: '1978年12月18日', event: '第十一屆三中全會,改革開放', } ] initHistoryLine(_historyEventList) /** * @description 繪制歷史軌跡曲線 * @param {Array} _eventList 事件列表 */ const initHistoryLine = function(_eventList) { let chartDom = document.getElementById('curve_box') let myChart = echarts.init(chartDom) let _xAsix = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let _yAsix = [1.5, 3.75, 4.5, 3.75, 3, 4.75, 5.5, 4.75, 4, 5.75, 6.5] let pointXList = [] // 根據事件數量,自定義每個點的 x 軸位置 switch(_eventList.length) { case 1: pointXList = [5] break; case 2: pointXList = [4, 8] break; case 3: pointXList = [2, 5, 8] break; case 4: pointXList = [2, 4, 6, 8] break; case 5: pointXList = [1, 3, 5, 7, 9] break; case 5: pointXList = [0, 2, 4, 6, 8, 10] break; default: pointXList = _xAsix.slice(0, _eventList.length) break; } // 標記點配置數組 let pointList = [] _eventList.forEach((item, index) => { // 標記點位置 let coordX = pointXList[index] let coordY = _yAsix[coordX] // 當前標記點 let cachePoint = { name: item.event, coord: [coordX, coordY], label: { show: true, align: 'center', verticalAlign: 'top', offset: [0, -30], formatter: function() { let _event = item.event; let _resEvent = ''; // 超出 10 位后換行 for (let i = 0; i < _event.length; i++) { _resEvent += _event[i]; if (!((i + 1) % 10)) _resEvent += '\n'; } // 富文本結果 let _result = [`{time|${item.time}}`, `{event|${_resEvent}}`].join( '\n' ); console.log(_result); return _result; }, rich: { time: { color: '#6a8dcd', lineHeight: 20 }, event: { color: '#fff', padding: [40, 0, 0, 0], lineHeight: 20 } } }, itemStyle: { color: '#6a8dcd' } } pointList.push(cachePoint) }) let option = { xAxis: { type: 'category', axisTick: { show: false, axisLine: { show: false } }, grid: { left: 0, top: 30, right: 0, bottom: 30 }, axisLabel: { show: false }, splitArea: { show: false }, show: false, boundaryGap: false }, yAxis: { type: 'value', axisTick: { show: false, axisLine: { show: false } }, axisLabel: { show: false }, splitArea: { show: false }, splitLine: { show: false }, scale: true }, series: [{ data: _yAsix, markPoint: { symbol: 'circle', symbolSize: 10, data: pointList }, symbol: 'none', type: 'line', smooth: true }] }; option && myChart.setOption(option); }