Доступ к параметрам массива из фигур d3.js

    <!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

//d3 code goes here 
//create some circles at random points on the screen

//create 50 circles of radius 20
//specify centre points randomly through the map function 
radius = 20;
var circle_data = d3.range(10).map(function() {
    return{
        x : Math.round(Math.random() * (width - radius * 2 ) + radius),
        y : Math.round(Math.random() * (height - radius * 2 ) + radius)
    }; 
}); 

//add svg circles 
var circles = d3.select("svg")
	.append("g")
	.attr("class", "circles")
	.selectAll("circle")
        .data(circle_data)
        .enter()
        .append("circle")
        .attr("cx", function(d) {return(d.x)})
        .attr("cy", function(d) {return(d.y)})
        .attr("r", radius)
        .attr("fill", "green");
//create drag handler with d3.drag()
//only interested in "drag" event listener, not "start" or "end"        
var drag_handler = d3.drag()
    .on("drag", function(d) {
          d3.select(this)
            .attr("cx", d.x = d3.event.x  )
            .attr("cy", d.y = d3.event.y  );
            });

//apply the drag_handler to our circles 
drag_handler(circles);
</script>

</style></body>
</html>

Вот мой код. Здесь есть кружочки которые можно таскать...(Drag 'N Drop)... Проблема в следующем.

Как создать массив из (кружочков) И ОБРАЩАТЬСЯ К КАЖДОЙ окружности ОТДЕЛЬНО ПО КООРДИНАТАМ?(Как c помощью стандартных методов узнать/установить текущие координаты каждого круга индивидуально)?:

Circle[1].setX=100;
Circle[1].setY =150;
MyX=Circle[0].getX();
MyY=Circle[0].getY();

???


Ответы (1 шт):

Автор решения: Stranger in the Q

Необходимо пройтись по массиву circle_data, поменять в объектах внутри x,y - в соответствии с новыми данными:

var newData =  [100,22,33,44,55,66,77,77,100,22,33,44,55,66,77,77,100,22,33,44]
circle_data.forEach(function(d, i) {
  d.x = newData[i*2]
  d.y = newData[i*2+1]
})

а затем повторить операцию присвоения данных выборке и обновление координат:

 circles.data(circle_data)
         .attr("cx", function(d) {return(d.x)})
         .attr("cy", function(d) {return(d.y)})

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

var radius = 20;
var circle_data = d3.range(10).map(function(i) {
  return {x: 100+i*50, y: rnd()};
});

var circles = d3.select("svg")
  .append("g")
  .attr("class", "circles")
  .selectAll("circle")
  .data(circle_data)
  .enter()
  .append("circle")
  .attr("cx", function(d) {return (d.x)})
  .attr("cy", function(d) {return (d.y)})
  .attr("r", radius)
  .style('transition', "200ms")
  .attr("fill", function(d) {
    return `hsl(${Math.random()*360},50%,50%)`
  })
  .call(d3.drag().on("start", function(d) {
          d3.select(this)
            .raise()
            .attr('stroke', 'black')
            .style('transition', "unset")
        }).on("drag", function(d) {
          d3.select(this)
            .attr("cx", d.x = d3.event.x)
            .attr("cy", d.y = d3.event.y);
        }).on("end", function(d) {
          d3.select(this)
            .attr('stroke', 'transparent')
            .style('transition', "200ms")
        })
  );

function upd () {

  var newData = [
    100, rnd(), 150, rnd(), 200, rnd(), 250, rnd(), 300, rnd(),
    350, rnd(), 400, rnd(), 450, rnd(), 500, rnd(), 550, rnd()
  ];

  circle_data.forEach(function(d, i) {
    d.x = newData[i * 2]
    d.y = newData[i * 2 + 1]
  });

  circles.data(circle_data)
    .attr("cx", function(d) {return (d.x)})
    .attr("cy", function(d) {return (d.y)})
}

function rnd() {
  return 20 + Math.random() * 110
}
<button onclick="upd()">upd()</button><br>
<svg width="600" height="150"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

→ Ссылка