2

问题:JavaScript 能够成功地在屏幕上绘制几条弧线,但它们在运行时消失了。我正在运行一个调用 ARC 函数的简单循环,但我不明白!?

我要做的就是逐步运行每个呼叫并睡觉!这可以用 JavaScript 之外的任何语言轻松完成,它是一个简单的过程循环。

问题是我的图表在消失之前出现了一瞬间。但是,如果我通过 JavaScript 调试器跟踪代码,它会一直工作,直到它再次消失!

沮丧的!我试图用 timeOut 来包装它,这样我就可以睡觉来显示一个缓慢的动画。我的朋友们到底发生了什么,这是 JavaScript 中的一个错误,还是我的基础不存在。当它如此合乎逻辑地编写时,我无法理解代码流。

https://jsfiddle.net/nd6gktmf/

var array_length = attack_list.length;
//EDITED: declare local variables
var coordinates,
    origin_longitude,
    origin_latitude,
    dest_longitude,
    dest_latitude;

for(var i=0; i < array_length; i++) {
   coordinates = attack_list[i];
   //EDITED: consider using dot notation
   origin_longitude = coordinates.origin.longitude;
   origin_latitude = coordinates.origin.latitude;
   dest_longitude = coordinates.destination.longitude;
   dest_latitude = coordinates.destination.latitude;

   draw_arc(origin_longitude, origin_latitude, dest_longitude, dest_latitude);
}    

这仅在调试模式下有效!什么....

function draw_arc(origin_longitude, origin_latitude, dest_longitude, dest_latitude) {
    var data_to_map = 
        [{ 
            origin: {
                latitude: origin_latitude,
                longitude: origin_longitude
            },
            destination: {
                latitude: dest_latitude,
                longitude: dest_longitude 
            }
        }]; 

   console.log("****** Begin******");
   console.log(origin_longitude);
   console.log(origin_latitude);
   console.log(dest_longitude);
   console.log(dest_latitude);
   console.log("****** End ******");

   election.arc(data_to_map, {strokeWidth: 2});
}
4

2 回答 2

2

正如凯文指出的那样:删除您添加到问题中的所有 javascript 代码(当然保留您的数据:electionattack_list)并将其替换为:

// loop over the attack_list
attack_list.forEach(function(attack_item, i){
  // now attack_item is one item from the array, i is the index in the array
  // we set up a timer FOR EACH item in the array
  setTimeout(function(){
    // we make an empty array, because election.arc needs an array,
    // eventhough we'll only send 1 item in it, we wrap it in an array
    var draw_list = [];
    draw_list.push(attack_item);
    // put the item into the array
    election.arc(draw_list,{strokeWidth: 2});
  }, i*2000);
  // note: the time is i*2000ms = i*2s
  // the "1st" item in attack_list is at index 0
  // so 0*2000=0 => it'll start drawing it immediately (t=0)
  // it animates for about 1s (t=1)
  // the last drawn line is still displayed (t=1..2)
  //
  // t=2: now the timer for the "2nd" item (i=1) starts drawing
  // but because we created a new empty array and only added the 2nd item
  // into it, when it draws, it erases everything that we drew before
  // and now you only see the 2nd item is getting animated.
  // etc...
});

https://jsfiddle.net/flocsy/nd6gktmf/3/

于 2016-02-04T19:59:49.173 回答
0

如果您查看文档,似乎您必须将所有弧线放在同一个数组中。

调用election.arc 可能会重新渲染整个图像,这就是为什么你最后只能看到最后一个。

于 2016-02-04T19:53:34.643 回答