如何在Google Timeline时间线图表中添加垂直线和文本标注?
Google Timeline 图表添加虚线和文本标注实现方案
原生Google Timeline组件没有内置标注功能,无需切换为AnnotatedTimeline,可通过SVG元素叠加的方式轻量实现需求:
实现逻辑
- 绑定图表
ready事件,确保图表完全渲染后再执行标注绘制,避免坐标计算错误 - 通过
chart.getChartLayoutInterface()获取布局实例,调用对应方法将日期、行索引转换为画布像素坐标 - 手动创建SVG虚线、文本元素,插入到图表生成的SVG容器中
- 如需适配窗口缩放,可在
resize事件触发时清空原有标注后重新绘制
完整可运行代码
<html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['timeline']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById('timeline'); var chart = new google.visualization.Timeline(container); var dataTable = new google.visualization.DataTable(); dataTable.addColumn({ type: 'string', id: 'President' }); dataTable.addColumn({ type: 'date', id: 'Start' }); dataTable.addColumn({ type: 'date', id: 'End' }); dataTable.addRows([ [ 'Washington', new Date(1789, 3, 30), new Date(1797, 2, 4) ], [ 'Adams', new Date(1797, 2, 4), new Date(1801, 2, 4) ], [ 'Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4) ] ]); // 图表渲染完成后添加标注 google.visualization.events.addListener(chart, 'ready', function () { // 替换为你需要标注的目标日期 const targetDate = new Date(1795, 0, 1); const layout = chart.getChartLayoutInterface(); // 计算目标日期对应的横向像素坐标 const xPos = layout.getXLocation(targetDate); // 获取图表区域的位置和尺寸 const chartArea = layout.getChartAreaBoundingBox(); const svg = container.querySelector('svg'); // 绘制贯穿图表的垂直虚线 const dashedLine = document.createElementNS('http://www.w3.org/2000/svg', 'line'); dashedLine.setAttribute('x1', xPos); dashedLine.setAttribute('x2', xPos); dashedLine.setAttribute('y1', chartArea.top); dashedLine.setAttribute('y2', chartArea.top + chartArea.height); dashedLine.setAttribute('stroke', '#ff0000'); dashedLine.setAttribute('stroke-width', '2'); dashedLine.setAttribute('stroke-dasharray', '5,5'); svg.appendChild(dashedLine); // 绘制文本标注 const label = document.createElementNS('http://www.w3.org/2000/svg', 'text'); label.setAttribute('x', xPos + 6); label.setAttribute('y', chartArea.top + 22); label.setAttribute('fill', '#ff0000'); label.setAttribute('font-size', '14px'); // 替换为你需要的标注文本 label.textContent = '重要时间节点'; svg.appendChild(label); }); chart.draw(dataTable); } </script> </head> <body> <div id="timeline" style="height: 180px;"></div> </body> </html>
你可以根据需求调整标注的颜色、尺寸、虚线样式、文本内容等属性,添加多个标注只需循环执行元素创建逻辑即可。
内容的提问来源于stack exchange,提问作者bart cubrich
相关产品推荐
相关产品推荐

