Results the preview

github pages

Vue and D3 characters

Drawing can be divided into two steps:

  1. Element coordinate calculation
  2. Data binding

Coordinate calculations only require some API, and d3 is used in this article. Data binding can be done with either D3 or VUE. D3 is implemented by manipulating dom, similar to jQuery. D3 proposes three concepts for data and DOM state: Update, Enter and Exit. If you are interested, you can see the official website. This article uses VUE for data binding

Summary: Element coordinates are calculated using the API provided by D3 and data binding is performed using VUE

Coordinate calculation

A tree is made up of nodes and links, and you only need to calculate the coordinates of these two elements

There are two common data structures for drawing a tree, one nested and one flat. As follows:

/ / nested
var treeData = {
    name: 'China'.children: [{
        name: 'Beijing'.children: [{
            name: 'haidian'
        }, {
            name: 'sun'}]}, {name: 'Shanghai'}};/ / flat
var flattenData = [{
    name: 'China'.parent: ' '
}, {
    name: 'Beijing'.parent: 'China'
}, {
    name: 'Shanghai'.parent: 'China'
}, {
    name: 'haidian'.parent: 'Beijing'
}, {
    name: 'sun'.parent: 'Beijing'
}]
Copy the code

For nested data, use d3.hierarchy() to compute coordinates, and for flat data, use D3.stratify (). The resulting structure looks like this (listing root nodes) :

var hierarchyNode = {
    depth: 0
    height: 2
    parent: null
    x: 60
    y: 0.data: {
       name: "China"And the children: []},children: []};Copy the code

After getting the root node, use descendants() to get all node information and links() to get all connection information. The structure of the node is as above, and the connection structure is as follows:

var link = {
    source: Node,
    target: Node
}
Copy the code

At this point, you have the coordinates of all the elements

Data binding

Using SVG

The node of the tree is rect + text, as follows:

<g :transform="rootTransform">
    <rect :width="nodeWidth" :height="nodeHeight" :fill="nodeFill"></rect>
    <text :fill="nodeTextColor" text-anchor="middle" dominant-baseline="middle"
        :y="nodeHeight / 2" :x="nodeWidth / 2">{{node.data.name}}</text>
</g>
Copy the code

The connection is path, as follows:

<g>
    <path :d="getLinkPath(link)" :stroke="linkStroke" fill="none" :stroke-width="linkStrokeWidth"></path>
</g>
Copy the code

code

talk is cheap show me the code

github/vue-d3-tree-example