我有以下的HTML结构。
<div id = 'divTest'>
<div id = 'divSVG'>
</div>
<button id ='bStep' type="button">Step</button>
<button id = 'bRun' type="button">Entire run</button>
</div>
我使用D3创建了10个随机位置的圆,这些圆位于一个想象的正方形内,该正方形的左上角位于(5, 5),边长为十。
const n = 10; // number of circles
//Creating random circles inside a square whose l = 10
//The top left corner of the square is at (5, 5)
const x_ini = 5;
const y_ini = 5;
const x_length = 10;
const y_length = 10
const dataset = [];
for(let i = 0; i < n; i ++) {
const randomNumberX = Math.random()
const x = randomNumberX * x_length + x_ini;
const randomNumberY = Math.random()
const y = randomNumberY * y_length + y_ini;
const pair = [x, y];
dataset[i] = pair;
}
const svg = d3.select('#divSVG')
.append('svg')
.attr('width', 300)
.attr('height', 300);
const circles = svg.selectAll('.circleTest')
.data(dataset)
.enter()
.append('circle')
.attr('cx', d => d[0])
.attr('cy', d => d[1])
.attr('class', 'circleTest')
.attr('r', 1)
.attr('fill', 'black');
我给步进按钮添加了一个功能,可以将一个圆移动到另一个虚拟圆上,并更改其类。
//Moves one circle to an imaginary square whose top left corner is at (100, 5)
d3.select('#bStep')
.on('click', () => {
const x_ini = 100;
const y_ini = 5;
const x_length = 10;
const y_length = 10;
const randomNumberX = Math.random()
const x = randomNumberX * x_length + x_ini;
const randomNumberY = Math.random()
const y = randomNumberY * y_length + y_ini;
const circle = d3.select('.circleTest')
.transition()
.duration(1000)
.attr('cx', x)
.attr('cy', y)
.attr('fill', 'red')
.attr('class', 'circleTest2')
});
我希望能够通过点击“整个运行”按钮,使所有圆圈不是同时移动,而是根据一些输入数据依次过渡。例如,基于“指令”向量,在第一个过渡中只移动一个圆圈,然后移动三个圆圈等等。我该如何实现这一点?
d3.select('#bRun')
.on('click', () => {
const instructions = [1, 3, 0, 2, 4, 1]
// Move all circles based on some input like 'instructions'
});
以下是一个可行的示例: https://jsfiddle.net/jandraor/91nwpb7a/42/