【发布时间】:2018-12-21 22:20:38
【问题描述】:
我正在尝试使用 d3 过渡来增量翻译以下方块。
然后,按下更新后,添加了两个方块,并将所有原始方块“推”到左边。
这是我卡住的部分。我想,在再次按下更新后,向数组中添加另外两个正方形,并将正方形序列推到更左的位置,如下所示。
但我下面的当前代码仅适用于第 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