首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >D3.js:如何计算任意元素的宽度和高度?

D3.js:如何计算任意元素的宽度和高度?
EN

Stack Overflow用户
提问于 2014-02-24 22:39:48
回答 2查看 117.4K关注 0票数 134

我需要知道SVG中任意g元素的确切宽度和高度,因为一旦用户单击它,我就需要在它周围绘制一个选择标记。

我在互联网上看到的类似于:d3.select("myG").style("width")。问题是元素并不总是有一个显式的width属性集。例如,当我在g中创建一个圆时,它将设置半径(r)而不是宽度。即使我在circle上使用window.getComputedStyle方法,它也会返回"auto“。

D3中有没有办法计算任意svg元素的宽度?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-24 23:04:28

对于SVG元素

使用像selection.node().getBBox()这样的东西,你会得到这样的值

代码语言:javascript
复制
{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

对于HTML元素

使用selection.node().getBoundingClientRect()

票数 258
EN

Stack Overflow用户

发布于 2017-11-01 16:45:28

有一次,当我不知道哪个元素当前存储在我的变量(svg或html)中时,我遇到了这个问题,但我需要获取它的宽度和高度。我创建了这个函数,并想分享它:

代码语言:javascript
复制
function computeDimensions(selection) {
  var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGGraphicsElement) { // check if node is svg element
    dimensions = node.getBBox();
  } else { // else is html element
    dimensions = node.getBoundingClientRect();
  }
  console.log(dimensions);
  return dimensions;
}

下面隐藏的代码片段中的小演示。我们使用相同的功能处理蓝色div和红色svg圆圈上的单击。

代码语言:javascript
复制
var svg = d3.select('svg')
  .attr('width', 50)
  .attr('height', 50);

function computeDimensions(selection) {
    var dimensions = null;
  var node = selection.node();

  if (node instanceof SVGElement) {
    dimensions = node.getBBox();
  } else {
    dimensions = node.getBoundingClientRect();
  }
  console.clear();
  console.log(dimensions);
  return dimensions;
}

var circle = svg
    .append("circle")
    .attr("r", 20)
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("fill", "red")
    .on("click", function() { computeDimensions(circle); });
    
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
代码语言:javascript
复制
* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  background: #ffd;
}

.div {
  display: inline-block;
  background-color: blue;
  margin-right: 30px;
  width: 30px;
  height: 30px;
}
代码语言:javascript
复制
<h3>
  Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21990857

复制
相关文章

相似问题

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