Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does path.bounds() work?

Tags:

d3.js

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.

like image 630
user3297662 Avatar asked Aug 14 '14 14:08

user3297662


1 Answers

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];
like image 108
Paulo Scardine Avatar answered Oct 21 '22 17:10

Paulo Scardine