d3.zoomTransform()

d3.zoomTransform(node)

Returns the current transform for the specified node. Note that node should typically be a DOM element, not a selection. (A selection may consist of multiple nodes, in different states, and this function only returns a single transform.) If you have a selection, call selection.node first:

var transform = d3.zoomTransform(selection.node());

In the context of an event listener, the node is typically the element that received the input event (which should be equal to event.transform), this:

var transform = d3.zoomTransform(this);

Internally, an element’s transform is stored as element.__zoom; however, you should use this method rather than accessing it directly. If the given node has no defined transform, returns the identity transformation. The returned transform represents a two-dimensional transformation matrix of the form:

k 0 tx
0 k ty
0 0 1

(This matrix is capable of representing only scale and translation; a future release may also allow rotation, though this would probably not be a backwards-compatible change.) The position ⟨x,y⟩ is transformed to ⟨x × k + tx,y × k + ty⟩. The transform object exposes the following properties:

  • x - the translation amount tx along the x-axis.
  • y - the translation amount ty along the y-axis.
  • k - the scale factor k.

These properties should be considered read-only; instead of mutating a transform, use transform.scale and transform.translate to derive a new transform. Also see zoom.scaleBy, zoom.scaleTo and zoom.translateBy for convenience methods on the zoom behavior. To create a transform with a given k, tx, and ty:

var t = d3.zoomIdentity.translate(x, y).scale(k);

To apply the transformation to a Canvas 2D context, use context.translate followed by context.scale:

context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);

Similarly, to apply the transformation to HTML elements via CSS:

div.style("transform", "translate(" + transform.x + "px," + transform.y + "px) scale(" + transform.k + ")");

To apply the transformation to SVG:

g.attr("transform", "translate(" + transform.x + "," + transform.y + ") scale(" + transform.k + ")");

Or more simply, taking advantage of transform.toString:

g.attr("transform", transform);

Note that the order of transformations matters! The translate must be applied before the scale.

doc_D3_Js
2016-11-24 10:27:38
Comments
Leave a Comment

Please login to continue.