Javascript 如何获取选定内容中所有文本元素的边界框值?
我有一个像这样的D3选择:Javascript 如何获取选定内容中所有文本元素的边界框值?,javascript,d3.js,Javascript,D3.js,我有一个像这样的D3选择: const labels = svg.selectAll('text').data(data); labels.enter().append('text') .attr('class', (d) => `label-${d.label}`) .attr('x', (d) => scale.x(d.time)) .attr('y', (d) => scale.y(d.value)) .text((d) => `${
const labels = svg.selectAll('text').data(data);
labels.enter().append('text')
.attr('class', (d) => `label-${d.label}`)
.attr('x', (d) => scale.x(d.time))
.attr('y', (d) => scale.y(d.value))
.text((d) => `${d.answer}`);
给定上述代码,如何创建所有文本元素的边界框?我希望做一些类似于Mike Bostock在以下代码中获取一个文本元素的边界框的事情:。但是,我希望获得每个元素的边界框值,以便为每个文本元素创建一个rect
元素 我会这样做:
...
.text((d) => `${d.answer}`)
.each(function(d){
var bbox = this.getBBox();
svg.append('rect')
.attr('x', bbox.x)
.attr('y', bbox.y)
.attr('width', bbox.width)
.attr('height', bbox.height)
.style('fill', 'none')
.style('stroke', 'steelblue');
});
运行代码:
var w=300,
h=300;
风险值数据=[
{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
},{
x:Math.random()*(w-100),
y:Math.random()*h,
t:偶然
}
]
var svg=d3.select('body')
.append('svg')
.attr('宽度',w)
.attr('高度',h);
const labels=svg.selectAll('text').data(数据);
标签。输入()
.append('文本')
.attr('class',(d)=>`label-${d.t}`)
.attr('x',(d)=>d.x)
.attr('y',(d)=>d.y)
.text((d)=>d.t)
.每个功能(d){
var bbox=this.getBBox();
append('rect')
.attr('x',bbox.x)
.attr('y',bbox.y)
.attr('width',bbox.width)
.attr('height',bbox.height)
.style('填充','无')
.style('stroke','steelblue');
});
我必须去.each((d,I,j)=>{const bbox=j[I].getBBox();…}
来完成这个任务,但是你的代码可以工作。Thanks@Benjamin,这是因为您使用的是胖箭头表示法,而不是常规函数。=>
,通过设计,禁止将此
传递到函数中。