PaperJS 从数组中删除符号

PaperJS remove symbol from array

我想创建一个函数,通过每次调用,创建另一个雨滴落下屏幕并在底部删除。

到目前为止,我设法用 PaperJS 做到了这一点,但是一旦我想在雨滴落到底部时删除它,整个函数就会崩溃,因为它丢失了数组 [i] 中的一个元素。

<script type="text/paperscript" canvas="myCanvas">
   
    
  // The amount of raindrops we want to spawn:
  var count = 0;

  // Drawing Layer for only the rain
  var rainlayer = new Layer();
  
  // Create a raindrop symbol, which we will use to place instances of later:
  var drop = new Path.Rectangle({
   x: 0,
   y: 0,
   width: 2,
   height: 16, 
   fillColor: 'white',
   opacity: 1
  });
  var symbol = new Symbol(drop);

  // Place the instances of the symbol when this function is called:
  function placeDrops(drops)
  {
   for (var i = 0; i < drops; i++) {
    // The center position is a random point in the top of the view:
    var center = new Point(Math.random()*view.size.width, 0);
    var placedSymbol = symbol.place(center);
   }
  }

  // The onFrame function is called up to 60 times a second:
  function onFrame(event) {
   // Run through the rainlayer's children list and change the position of the placed symbols:
   for (var i = 0; i < count; i++) {
                    // safe the current rain drop as the item var so we don't have to type too much code
        var item = rainlayer.children[i];
     // Move the item 5 times of its width to the bottom.
     item.position.y += item.bounds.width * 5;
     // If the item has left the view on the bottom, remove it from the canvas
     if (item.bounds.bottom > view.size.height) {
                        //!!!
                        //THIS IS WHAT CAUSES THE ERROR 'TypeError: item is undefined' as soon as 
                        //the first rain drop hits the bottom
                        //!!!
      item.remove();
      rainlayer.removeChildren(i);
     }
    }
  }
  
  function onMouseDown(event) 
  {
   count = count + 1;
   placeDrops(1);
  }
</script>

一旦第一滴雨落到底部,它就会被移除(应该如此)但是当循环再次回到它的位置时,没有 rainlayer.children[i ]; 留在这个位置可以保存到 var item,所以我得到控制台错误 TypeError: item is undefined 以我的理解。

我对这一切还很陌生,所以可能有更简单的方法让事情发生或解决这个错误。非常感谢您的帮助!

我认为问题在于您使用行 rainlayer.removeChildren(i).

rainlayer 中删除了所有子项

您只需要行 item.remove() - 从项目中删除项目,使其不再位于图层中。无需从图层中移除子项。

rainlayer.removeChildren(from [, to]) 是带有参数的语法,因此当使用 from = 0.

调用时,它会从图层中删除所有子项