首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在绘制文本之前计算文本宽度

在绘制文本之前计算文本宽度
EN

Stack Overflow用户
提问于 2015-03-13 19:58:12
回答 1查看 29.7K关注 0票数 35

我想在旁边显示一个带有text标签的rectrect的宽度应该延伸到svg容器的宽度,减去文本的宽度,文本的宽度是动态的,可以是任意可变的长度。

JSFiddle

代码语言:javascript
复制
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计算文本的宽度?或者,我如何定位和调整依赖于可变长度文本尺寸的元素?

EN

回答 1

Stack Overflow用户

发布于 2016-02-13 06:08:24

我知道你问过关于D3的问题,但这可能是你的问题的本地解决方案。

HTML5 canvas 2D上下文具有一些用于测量文本的内置功能。您也许能够利用它来测量其他API的文本,比如SVG。如果它不是100%准确,那么它肯定与正确答案成正比。

代码语言:javascript
复制
var BrowserText = (function () {
    var canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

    /**
     * Measures the rendered width of arbitrary text given the font size and font face
     * @param {string} text The text to measure
     * @param {number} fontSize The font size in pixels
     * @param {string} fontFace The font face ("Arial", "Helvetica", etc.)
     * @returns {number} The width of the text
     **/
    function getWidth(text, fontSize, fontFace) {
        context.font = fontSize + 'px ' + fontFace;
        return context.measureText(text).width;
    }

    return {
        getWidth: getWidth
    };
})();

// Then call it like this:
console.log(BrowserText.getWidth('hello world', 22, 'Arial')); // 105.166015625
console.log(BrowserText.getWidth('hello world', 22)); // 100.8154296875
票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29031659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档