【问题标题】:How can I get the heights of each in a group of generated D3.js elements?如何获得一组生成的 D3.js 元素中每个元素的高度?
【发布时间】:2019-02-03 03:42:49
【问题描述】:

我的问题是这个问题的延伸: D3.js: How to get the computed width and height for an arbitrary element?

然而,就我而言,我想获得由 D3 创建的 元素的计算高度。

组中的项目创建如下:

const boxGroup = mainArea.selectAll('.boxes-user')
  .data(data)
  .enter()
  .append("g")
  .attr('id', (d) => 'bars-user-' + d[0].userId )
  .attr("transform", (d) => {
    currentRow = currentRow + 1;
    return "translate( 0, " + ((rowHeight * currentRow) + (20 * currentRow)) + ")"
  });

这会创建多个<g> 元素。 data 数组中的每一项对应一个。

我希望能够确定每个生成的.boxes-user 组的计算最终高度。

这可能吗?如果是,如何?

【问题讨论】:

  • 如果您在元素加载到 DOM 后获取此信息,您可以使用 document.getElementById('your-elemet-id').getBoundingClientRect().height 也可能对这个包感兴趣 npmjs.com/package/svg-path-properties
  • 我希望它成为 D3 代码的一部分,因为我想使用这些信息来定位其他元素
  • 在回调中使用全局变量currentRow 是非常糟糕的做法。你有(d,i) => { ... } 来获取索引
  • @rioV8 谢谢我会修复它!

标签: javascript d3.js dom svg


【解决方案1】:

计算<g> 元素的宽度和高度的方法完全相同,即使用getBBox()。由于所引用的链接没有提供示例,这里有一个控制台记录包含随机元素的 <g> 元素的高度。

var data = [{type: 'text',value: "Test1"}, {type: 'rect', value: {w: 40, h: 70}}, {type: 'circle', value: {r: 12, x: 120}}];

const boxGroup = d3.select('svg').selectAll('.boxes-user')
  .data(data)
  .enter()
  .append("g").classed('boxes-user', true)
  .attr("transform", function (d, i) {
    return "translate(" + (i * 100) + ", 30)";
  }).each(function (d) {
		if(d.type === 'circle') {
    	d3.select(this).append('circle').style('fill', d.value.color || 'steelblue')
         .attr('r', d.value.r || 10).attr('cx', d.value.x || 20);
    } else if(d.type === 'rect') {
  		d3.select(this).append('rect').attr('width', d.value.w || 40).attr('height', d.value.h || 20);  	
    } else {
	    d3.select(this).append('text').text(d.value);
    }    
    // "this" is the group element here. Computing height for the same
    console.log('height of ' + d.type + ': ' + d3.select(this).node().getBBox().height);
  });
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>

<svg width="700" height="500"></svg>

确保在计算尺寸之前添加其中的元素,否则最终会导致结果为 0。希望这可以清除它。

【讨论】:

猜你喜欢
  • 2017-02-27
  • 2018-01-12
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
  • 2017-08-16
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多