简体   繁体   中英

How do I make the position of the text dynamic with resize on an svg element?

I am creating a sort of bar chart and I am trying to include data labels. I have drawn the text containing the appropriate values but it doesn't respond well to being resized. Instead of moving with the bar it just stays still till the page is refreshed.

Note that the numbers should be right above the green and red bars:

图片

this.svg.selectAll("text.dataLabels")        
    .data(viewModel.dataPoints)
    .enter()
    .append("text")
    .attr("class","dataLabels")
    .attr({
        y: (dataPoint: BarChartDataPoint) => yScale(<number>dataPoint.value)-BarChart.Config.dataLabelShift.vertical,
        x: (dataPoint: BarChartDataPoint) => xScale(dataPoint.category)+BarChart.Config.dataLabelShift.horizontal
    })
    .attr("text-anchor", "middle")
    .text((dataPoint: BarChartDataPoint) => <string>dataPoint.value)
    .style({
        'font-family': 'sans-serif',
        'font-weight':'bold',
        'fill': 'grey'
    }); 

Instead of working directly with the parent svg object and appending a text element directly onto it, instead I create a separate element:

 private dataLabels: d3.Selection<SVGElement>;
    this.dataLabels = this.svg
            .append('g')
            .classed('dataLabels',true)

I then appended the text elements to a new object:

let dataLabelEl = this.dataLabels
                .selectAll('text.dataLabels')
                .data(viewModel.dataPoints);

            dataLabelEl
                .enter()
                .append('text')
                .classed('dataLabels', true);

            dataLabelEl
                .attr({
                    y: (dataPoint) => yScale(<number>dataPoint.value)-BarChart.Config.dataLabelShift.vertical,
                    x: (dataPoint) => xScale(dataPoint.category)+BarChart.Config.dataLabelShift.horizontal
                })
                .attr("text-anchor", "middle")
                .text((dataPoint) => <string>dataPoint.value)
                .style({
                    'font-family': 'sans-serif',
                    'font-weight':'bold',
                    'fill': 'grey'
                });

This works!

您可以设置文本的x和y位置,并且永远不会使调整大小后的干扰遵循链接

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM