【问题标题】:d3.js: incremental transition translationd3.js:增量转换翻译
【发布时间】:2018-12-21 22:20:38
【问题描述】:

我正在尝试使用 d3 过渡来增量翻译以下方块。

首先,我最初有 6 个方块。

然后,按下更新后,添加了两个方块,并将所有原始方块“推”到左边。

这是我卡住的部分。我想,在再次按下更新后,向数组中添加另外两个正方形,并将正方形序列推到更左的位置,如下所示。

但我下面的当前代码仅适用于第 1 步到第 2 步,不适用于第 3 步。有人可以帮忙吗?谢谢。

<head>
    <script src="https://d3js.org/d3.v3.min.js"></script> 
</head>


<body style="background-color:black;">
    <button id="update1" class="btn  btn btn-sm">Update</button>
</body>

<script>
    var links = [1,2,3,4,5,6];


    svg = d3.select('body').append("svg")
            .attr("width", 600)
            .attr("height", 80);

    // function to add squares    
    var update = function(){
        rect = svg.append('g').selectAll('rect')
        text = svg.append('g').selectAll('text')


        links
        rect = rect.data(links)
        rect.enter().append("rect")
            .attr("x", function(e, counter){return 100  * (counter)})
            .attr("y", 20)
            .attr({"width":20, "height":20})
            .attr({"fill":'red', "opacity":"1"})


        text = text.data(links)
        text.enter().append('text')
            .attr("x", function(e, counter){return 100  * (counter) + 7})
            .attr("y", 18)
            .attr({"font-size":14, "fill":"white", "font-weight":"bold"})
            .text(function(e) {return e})
    };

    // initial squares
    update()

    // update with two squares
    d3.select("#update1").on("click", function() {
        var update1 = [7,8];

        // insert new data to array
        update1.forEach(function(i){
            links.push(i);
        })

        // remove existing squares in display
        d3.selectAll('svg>g').remove()

        // add new squares
        update()

        shift = update1.length // get no. of new squares
        var translate = "translate(" + -100 * shift + "," + "0" + ')'; // push it by existing no. of new squares
        d3.selectAll('rect,text').transition().attr('transform',translate).duration(1000)
    })

</script>

【问题讨论】:

    标签: d3.js transition


    【解决方案1】:

    以下是我在您的代码中看到的一些问题:

    • 您仅在按下“#update1”按钮时才添加链接 [7, 8],因此需要将其更改为添加一个比上次按下的“链接”高 +1 的数字,以及高出 +2。
    • 当您调用“更新”函数时,您正在一个更大的数组上运行,但仍基于它们的索引定位它们,在函数调用中使用“计数器”参数设置“矩形”的“x”属性和您正在创建的“文本”对象。

    我想我已经添加了你想要的功能,这是一个 codepen:https://codepen.io/anon/pen/MBaoxb?editors=0011

    我所做的更改如下:

    更改了它,以便添加的新链接可以根据推入数组的最后一个数字增加。

    **Line 33:** var update1 = [links[links.length-1] + 1, links[links.length-1] + 2];
    

    从数组中删除了前 2 个链接(因此可以从索引中设置位置,因为“更新”函数中的代码当前设置为执行此操作)。

    **Line 56:**     links = links.splice(2, links.length);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2019-05-27
      • 1970-01-01
      • 2010-10-03
      相关资源
      最近更新 更多