简体   繁体   中英

How to animate drawing a sequence of line segments

I would like to draw a point and after 1 sec or so I would like to draw the next point. Is this somehow possible:

I already tried:

function simulate(i) {
  setTimeout(function() { drawPoint(vis,i,i); }, 1000);
}

for (var i = 1; i <= 200; ++i)
  simulate(i);

function drawPoint(vis,x,y){
  var svg = vis.append("circle")
    .attr("cx", function(d) {
      console.log(x);
      return 700/2+x;
    })
    .attr("cy", function(d) {
      return 700/2+y;
    })
   .attr("r", function(d) {
     console.log(x);
     return 6;
   });
}

Unfortunately, this is not working. It just draws the whole line immediately.

This will not work, because the for loop will immediately run to the end, the setTimeouts will be scheduled simultaneously and all the functions will fire at the same time.

Instead of that, do this:

var i = 1;
(function loop(){
    if(i++ > 200) return;
    setTimeout(function(){
        drawPoint(vis,i,i); 
        loop()
    }, 1000)
})();

Explanation:

This IIFE will run for the first time with i = 1 . Then, the if increases i (doing i++ ) and checks if it is bigger than 200. If it is, the function loop returns. If it's not, a setTimeout is scheduled, which calls drawnPoint and the very function loop again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM