如何在Highcharts图表中动态修改SVG元素属性?
解决方案
要在外部函数中访问Highcharts内创建的可拖拽SVG矩形,核心是打破局部作用域限制,将矩形对象挂载到chart实例上:
- 挂载矩形对象到chart实例:在
chart.events.load事件中创建矩形后,将其赋值给chart的自定义属性,让外部能通过chart实例访问到它。 - 外部函数中修改属性:在拥有
chart变量的外部函数里,通过挂载的属性调用attr()方法修改矩形属性。
修改后的完整代码
JavaScript
var chart = Highcharts.chart('container', { chart: { events: { load() { var chart = this, lineWidth = 2, draggablePlotLine = chart.renderer.rect(100, chart.plotTop, lineWidth, chart.plotHeight) .attr({ fill: 'blue' }) .add(); // 将矩形对象挂载到chart实例,供外部访问 chart.draggablePlotLine = draggablePlotLine; chart.container.onmousemove = function(e) { if (draggablePlotLine.drag) { let normalizedEvent = chart.pointer.normalize(e), extremes = { left: chart.plotLeft, right: chart.plotLeft + chart.plotWidth }; if ( e.chartX >= extremes.left && e.chartX <= extremes.right ) { draggablePlotLine.attr({ x: e.chartX }) } } } draggablePlotLine.element.onmousedown = function() { draggablePlotLine.drag = true } draggablePlotLine.element.onmouseup = function() { draggablePlotLine.drag = false } } } }, series: [{ name: 'Installation', data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }], }); // 外部函数:动态修改矩形位置 function changeLinePosition() { // 替换为你的特定判断条件 if (true) { // 替换为目标x值,示例为图表左侧偏移200px的位置 chart.draggablePlotLine.attr({ x: chart.plotLeft + 200 }); } } // 可调用changeLinePosition()测试效果 // changeLinePosition();
CSS
#container { min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto }
HTML
<script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://rawgithub.com/highcharts/draggable-points/master/draggable-points.js?1"></script> <div id="container"></div>
内容的提问来源于stack exchange,提问作者Abhay Kaushik
相关产品推荐
相关产品推荐

