programing tip

D3.js : 임의의 요소에 대해 계산 된 너비와 높이를 얻는 방법은 무엇입니까?

itbloger 2020. 7. 25. 10:40
반응형

D3.js : 임의의 요소에 대해 계산 된 너비와 높이를 얻는 방법은 무엇입니까?


사용자가 클릭하면 선택 마커를 그 주위에 그려야하기 때문에 임의의 g요소 의 너비와 높이를 정확히 알아야 SVG합니다.

인터넷에서 본 것은 다음과 같습니다 d3.select("myG").style("width").. 문제는 요소에 항상 명시적인 너비 속성이 설정되지는 않는다는 것입니다. 예를 들어, 안에 원을 만들면 너비 대신 g반경 ( r)이 설정됩니다. 에서 window.getComputedStyle메소드를 사용하더라도 circle"auto"를 반환합니다.

에서 임의의 svg요소 의 너비를 계산하는 방법이 D3있습니까?

감사합니다.


SVG 요소

같은 것을 사용하면 다음과 같은 selection.node().getBBox()가치가 있습니다

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

HTML 요소

사용하다 selection.node().getBoundingClientRect()


.getBoundingClientRect () 는 뷰포트를 기준으로 요소의 크기와 위치를 반환합니다.

  • 왼쪽 오른쪽
  • 위, 아래
  • 높이 너비

예 :

var element = d3.select('.elementClassName').node();
element.getBoundingClientRect().width;

일단 내 변수 (svg 또는 html)에 어떤 요소가 저장되어 있는지 알지 못했을 때 문제에 직면했지만 너비와 높이를 가져와야했습니다. 이 기능을 만들고 공유하고 싶습니다.

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

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

아래 숨겨진 스 니펫의 작은 데모. 동일한 기능으로 파란색 div와 빨간색 svg 원을 클릭 처리합니다.

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) });
* {
  margin: 0;
  padding: 0;
  border: 0;
}

body {
  background: #ffd;
}

.div {
  display: inline-block;
  background-color: blue;
  margin-right: 30px;
  width: 30px;
  height: 30px;
}
<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>

참고 URL : https://stackoverflow.com/questions/21990857/d3-js-how-to-get-the-computed-width-and-height-for-an-arbitrary-element

반응형