D3

d3: 力导向图既可以放缩也可以拖拽

2019-07-30  本文已影响0人  zackxizi
<template>
    <div class="force" ref="force"></div>
</template>

<script>
    let svg = null;
    let force = null;
    let links = null;
    let nodes = null;
    let texts = null;
    let linePath = d3.svg.line();
    export default {
        name: "force",
        data() {
            return {
                nodesData: [],
                linksData: []
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.renderForce();
            })
        },
        computed: {
            width() {
                return this.$refs.force.getBoundingClientRect().width;
            },
            height() {
                return this.$refs.force.getBoundingClientRect().height;
            }
        },
        methods: {
            renderForce() {
                this.initSvg();
                this.links();
                this.nodes();
                this.texts();
                this.initForce();
                force.start();
                this.refreshForce();
            },
            /**
             * 初始化svg
             */
            initSvg() {
                // 创建svg
                svg = d3.select('.force')
                    .append('svg')
                    .attr('width', this.width)
                    .attr('height', this.height)
                    // 在svg上添加放缩行为
                    .call(d3.behavior.zoom()
                        .on('zoom', this.zoomed)) // 监听放缩中
                    .append('g')
                    .attr('id', 'forceWrapper');
            },
            /**
             * 初始化力导向图
             */
            initForce() {
                force = d3.layout.force()
                    .nodes(this.nodesData) // 设定或获取力导向图的节点数组
                    .links(this.linksData) // 设置或获取力导向如布局的连线数组
                    .size([this.width, this.height]) // 设定或获取力导向图的作用范围
                    .linkDistance(200) // 设置连线的距离
                    .charge(-400)// 设置节点的电荷数
                    .on('tick', this.tick); // 动画的计算进入下一步
            },
            /**
             * 监听放缩中
             */
            zoomed() {
                /*================>>>>>>>>>>>>>>>>>>> 重 点 <<<<<<<<<<<<<<<<<<<<<<=================*/
                // 监听svg的放缩,该改变id为forceWrapper的
                d3.select('#forceWrapper')
                    .attr('transform', `
                    translate(${d3.event.translate}) scale(${d3.event.scale})
                    `)
            },
            /**
             *
             */
            tick() {
                // 设置node、link text节点关于位置的属性
                nodes.attr('cx', function (d) {
                    return d.x;
                }).attr('cy', function (d) {
                    return d.y;
                });
                texts
                    .attr('dx', function (d) {
                        return d.x;
                    })
                    .attr('dy', function (d) {
                        return d.y + 35;
                    })
                    .text(d => {
                        return d.name;
                    });
                links.attr('d', function (d) {
                    let lines = [];
                    // 这是使用了线段生成器,生成path的路径
                    lines.push([d.source.x, d.source.y], [d.target.x, d.target.y]);
                    return linePath(lines);
                })
            },
            /**
             * 创建link
             */
            links() {
                // 切记这里要svg.selectAll('.link') 否则会将path元素创建到body底下 而非svg内
                links = svg.selectAll('.link')
                    .append('path')
                    .attr('class', 'link')
            },
            /**
             * 创建node节点
             */
            nodes() {
                nodes = svg.selectAll('.circle')
                    .append('circle')
                    .attr('class', 'circle')
            },
            /**
             * 创建text
             */
            texts() {
                texts = svg.selectAll('.text')
                    .append('text')
                    .attr('class', 'text')
            },
            /**
             * 刷新页面数据
             */
            refreshForce() {
                let newNodeData = [{name: "桂林"}, {name: "广州"},
                    {name: "厦门"}, {name: "杭州"},
                    {name: "上海"}, {name: "青岛"},
                    {name: "天津"}];
                let newlinksData = [{source: 0, target: 1}, {source: 0, target: 2},
                    {source: 0, target: 3}, {source: 1, target: 4},
                    {source: 1, target: 5}, {source: 1, target: 6}];
                // 添加或者修改node数据或者link数据,一定要在原有数组内添加或者删除,不能 this.nodesData = newNodeData这样,想要知道为什么请查看引用类型的特性(堆和栈)
                this.nodesData.push(...newNodeData);
                this.linksData.push(...newlinksData);

                // 重新将数据绑定到link和node上
                links = links.data(force.links());
                links.enter()
                    .append('path')
                    .attr('class', 'link')
                    .attr('stroke-dasharray', '5 5')
                    .attr("stroke", '#ccc')
                    .attr('stroke-width', '3px');
                links.append('animate')
                    .attr('attributeName', 'stroke-dashoffset')
                    .attr('from', '0')
                    .attr('to', '-100')
                    .attr('begin', '0s')
                    .attr('dur', '3s')
                    .attr('repeatCount', 'indefinite');
                links.exit().remove();


                nodes = nodes.data(force.nodes());
                // 数据没有对应的node添加circle node
                nodes.enter()
                    .append('circle')
                    .attr('class', 'circle')
                    .attr('r', 20)
                    .attr('fill', '#293152')
                    .style('cursor', 'pointer')
                    .call(force.drag()
                        .on('dragstart', function () {
                            /*=============重点========*/
                            // 切记 在force拖拽开始时组织默认时间
                            d3.event.sourceEvent.stopPropagation()
                        }));
                // 将多余的node节点删除
                nodes.exit().remove();


                texts = texts.data(force.nodes());
                texts.enter()
                    .append('text')
                    .attr('class', 'mergeText')
                    .style('fill', '#000')
                    .style('font-size', 12)
                    .style('cursor', 'pointer')
                    .style('font-weight', 'lighter')
                    .style('text-anchor', 'middle')
                    .call(force.drag);
                texts.exit().remove();
                force.start();
            }
        }
    }
</script>

<style scoped>

</style>

重点:

 .call(force.drag()
  .on('dragstart', function () {
     /*=============重点========*/
    // 切记 在force拖拽开始时组织默认时间
    d3.event.sourceEvent.stopPropagation()
}));
zoomed() {
                /* >>>>>>>>>>>>>>>>>>> 重 点 <<<<<<<<<<<<<<<<<<<<<< */
                // 监听svg的放缩,该改变id为forceWrapper的
                d3.select('#forceWrapper')
                    .attr('transform', `
                    translate(${d3.event.translate}) scale(${d3.event.scale})
                    `)
            }
上一篇 下一篇

猜你喜欢

热点阅读