Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

reactjs - How to redraw text rendered using SVGRenderer in Highcharts React?

I am using the SVGRenderer to draw the total value in the center of donut chart shown below:

enter image description here

The code to do this is shown below (please see CodeSandbox here)

export const PieChart = ({ title, totalLabel, pieSize, pieInnerSize, data }: PieChartProps) => {
    const chartRef = useRef(null);
    const [chartOptions, setChartOptions] = useState(initialOptions);

    useEffect(() => {
        // set options from props
        setChartOptions({...});

        // compute total
        const total = data.reduce((accumulator, currentValue) => accumulator + currentValue.y, 0);

        // render total
        const totalElement = chart.renderer.text(total, 0, 0).add();
        const totalElementBox = totalElement.getBBox();

        // Place total
        totalElement.translate(
            chart.plotLeft + (chart.plotWidth - totalElementBox.width) / 2,
            chart.plotTop + chart.plotHeight / 2
        );
        ...
    }, [title, totalLabel, pieSize, pieInnerSize, data]);

    return (
        <HighchartsReact
            highcharts={Highcharts}
            containerProps={{ style: { width: '100%', height: '100%' } }}
            options={chartOptions}
            ref={chartRef}
        />
    );
};

However this approach has two issues:

  1. When chart is resized, the total stays where it is - so it is no longer centered inside the pie.

enter image description here

  1. When the chart data is changed (using the form), the new total is drawn over the existing one.

enter image description here

How do I solve these issues? With React, I expect the chart to be fully re-rendered when it is resized or when the props are changed. However, with Highcharts React, the chart seems to keep internal state which is not overwritten with new props.

question from:https://stackoverflow.com/questions/65873505/how-to-redraw-text-rendered-using-svgrenderer-in-highcharts-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can suggest two options for this case:

  1. Use the events.render callback, destroy and render a new label after each redraw:

Demo: https://jsfiddle.net/BlackLabel/ps97bxkg/

  1. Use the events.render callback to trasnlate those labels after each redraw:

Demo: https://jsfiddle.net/BlackLabel/6kwag80z/

Render callback triggers after each chart redraw, so it is fully useful in this case - more information API: https://api.highcharts.com/highcharts/chart.events.render


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...