observablehq / stdlib

The Observable standard library.
https://observablehq.com/@observablehq/standard-library
ISC License
966 stars 83 forks source link

How to getBBox() on nodes #170

Closed robert-moore closed 4 years ago

robert-moore commented 4 years ago

Reproduction

{
  const svg = d3.create('svg')
  const g = svg.append('g')
  g.append('text').text('Some text here')
  const gWidth = labelGroup.node().getBBox().width;
}

This will work find in the browser but will not work through observable and d3.create()

(non-minimal) example in production: https://observablehq.com/@robert-moore/stacked-bar-with-labels

mbostock commented 4 years ago

This doesn’t work because you’re trying to call getBBox before the element is part of the DOM.

One way to fix this is to use a generator cell and yield the element before trying to read its dimensions:

{
  const svg = d3.create('svg');
  const g = svg.append('g');
  g.append('text').text('Some text here');
  yield svg.node();
  const gWidth = labelGroup.node().getBBox().width;
}

If you have further questions, please ask over in the forum rather than on GitHub. Thank you!