我想在旁边显示一个带有text
标签的rect
。rect
的宽度应该延伸到svg容器的宽度,减去文本的宽度,文本的宽度是动态的,可以是任意可变的长度。
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计算文本的宽度?或者,我如何定位和调整依赖于可变长度文本尺寸的元素?
发布于 2016-02-13 06:08:24
我知道你问过关于D3的问题,但这可能是你的问题的本地解决方案。
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
https://stackoverflow.com/questions/29031659
复制相似问题