gpt4 book ai didi

d3.js - 在绘制文本之前计算文本的宽度

转载 作者:行者123 更新时间:2023-12-03 22:16:14 26 4
gpt4 key购买 nike

我想显示 recttext旁边的标签。 rect 的宽度应该拉伸(stretch)到 svg 容器的宽度,减去文本的宽度,这是动态的,可以是任何可变长度。

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 计算文本的宽度?或者我如何定位和调整取决于可变长度文本尺寸的元素?

最佳答案

我知道您询问了 D3,但这可能是您问题的 native 解决方案。

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

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

关于d3.js - 在绘制文本之前计算文本的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29031659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com