5

Can someone tell me what exactly happens with the following code? I understand it is used for zooming, but what does the 2-d array of bounds do in this context?

var bounds = path.bounds(d), 
    dx = bounds[1][0] - bounds[0][0], 
    dy = bounds[1][1] - bounds[0][1],
    x = (bounds[0][0] + bounds[1][0]) / 2,
    y = (bounds[0][1] + bounds[1][1]) / 2,
            scale = .9 / Math.max(dx / width, dy / height),
    translate = [width / 2 - scale * x, height / 2 - scale * y];

Thanks in advance.

Belphegor
  • 4,456
  • 11
  • 34
  • 59
user3297662
  • 53
  • 1
  • 6
  • This method returns the bounding box (the minimum rectangle that encloses the object), it is an easy way to calculate the center. – Paulo Scardine Aug 14 '14 at 14:39
  • https://github.com/mbostock/d3/wiki/Geo-Paths#path_bounds – Paulo Scardine Aug 14 '14 at 14:41
  • So the `path.bounds()` output is `[[left,top],[right,bottom]]`. Different from `geo.path.bounds()` output `[[left, bottom], [right, top]]` as by [API](https://github.com/mbostock/d3/wiki/Geo-Paths#bounds). May be need to put it in the github api. – Hugolpz Apr 21 '15 at 15:59

1 Answers1

12

It is well documented:

Computes the projected bounding box (in pixels) for the specified feature. This is handy for, say, zooming in to a particular feature. This method observes any clipping and resampling performed by the projection stream.

As you can see in the picture below, the center is the point half the height and half the width. For the zooming calculations, see my answer to this question about centering an object.

enter image description here


Here is the new (2016) documentation link for D3 v4 and here is an explanation of the structure of the output array:

The bounding box is represented by a two-dimensional array: [[x₀, y₀], [x₁, y₁]], where x₀ is the minimum x-coordinate, y₀ is the minimum y-coordinate, x₁ is maximum x-coordinate, and y₁ is the maximum y-coordinate.

For width and height:

//       x-max          x-min
width  = bounds[1][0] - bounds[0][0];

//       y-max          y-min
height = bounds[1][1] - bounds[0][1];
Community
  • 1
  • 1
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153