首页 > 解决方案 > Highcharts:与图表一起自动缩放渲染形状?

问题描述

我使用chart.renderer.rect() 在图表上放置了一个盒子形状。当我水平调整页面大小时,我希望该框变得更窄(与图表相同)。

我可以在检查器中看到,所有 SVG 图表元素的 width 属性在我调整页面大小时都发生了变化,而不是我渲染的盒子形状。他们是怎么做到的?是否有一些属性我必须添加到我渲染的盒子形状中?

我还注意到add() 方法需要一个父级,但我无法弄清楚如何从要添加它的图表中获取 SVGElement,而且我不确定设置父级是否会给我想要的自动缩放反正。

标签: javascriptsvghighcharts

解决方案


您可以存储对元素的引用并编辑它的属性,例如基于轴值。例子:

chart: {
    events: {
        render: function() {
            const chart = this;
            const xAxis = chart.xAxis[0];
            const yAxis = chart.yAxis[0];
            const startX = xAxis.toPixels(1);
            const startY = yAxis.toPixels(7);
            const width = xAxis.toPixels(6) - startX;
            const height = yAxis.toPixels(4) - startY;

            if (!chart.customRect) {
                chart.customRect = chart.renderer.rect().attr({
                    'stroke-width': 2,
                    stroke: 'red',
                    fill: 'yellow'
                }).add();
            }

            chart.customRect.attr({
                x: startX,
                y: startY,
                width,
                height
            });
        }
    }
}

现场演示:http: //jsfiddle.net/BlackLabel/p6743jam/

API参考:

https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr

https://api.highcharts.com/class-reference/Highcharts.Axis#toPixels


推荐阅读