在绘制文本之前计算文本的宽度 [英] Calculate width of text before drawing the text

查看:118
本文介绍了在绘制文本之前计算文本的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示一个 rect ,旁边有一个文本标签。 rect 的宽度应该延伸到svg容器的宽度,减去文本的宽度,这是动态的,可以是任何可变长度。

I want to display a rect with a text label next to it. The width of the rect should stretch to the width of the svg container, less the width of the the text, which is dynamic and can be of any variable length.

JSFiddle

var text = 'Foobar';
var textWidth = 50; //how to calculate this?
var plotWidth = 400;
var barWidth = plotWidth-textWidth;

var plot = d3.select(container)
        .insert("svg")
        .attr('width', plotWidth)
        .attr('height', 50);

plot.append("rect")
    .style("fill", "steelblue")
    .attr("x", 0)
    .attr("width", barWidth)
    .attr("y", 0)
    .attr("height", 50);

plot.append("text")
    .attr("x", barWidth)
    .attr("y", 28)
    .text(text);

如何在绘制之前使用D3计算文本的宽度?

How do I calculate the width of the text using D3, before it is drawn? Or how do I otherwise position and size elements that depend on the dimensions of variable length text?

推荐答案

我有一个类似的问题,一个包含元素和文本之间的大量交互的复杂图表,它需要知道之前显示任何元素的文本宽度

I had a similar problem in a complex chart with lots of interactions between elements and text, which required knowing the text width before displaying any element.

我诉诸创建虚拟文本获取其宽度并立即删除它。注意每个中函数的最后一行代码。

I resorted to creating a dummy text to grab its width and immediately remove it. Note the last line of code of the function in each.

var textData = ['a', 'b', 'c']    // your text here

var textWidth = []

svg.append('g')
    .selectAll('.dummyText')
    .data(textData)
    .enter()
    .append("text")
    .attr("font-family", "sans-serif")
    .attr("font-size", "14px")
    //.attr("opacity", 0.0)      // not really necessary
    .text(function(d) { return d})
    .each(function(d,i) {
        var thisWidth = this.getComputedTextLength()
        textWidth.push(thisWidth)
        this.remove() // remove them just after displaying them
    })

console.log(textWidth) // this array contains the on-screen width of each text element

这篇关于在绘制文本之前计算文本的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆