Я хотел создать функцию, которая при каждом вызове создает еще одну каплю дождя, которая падает на экран и удаляется, оказавшись внизу.
До сих пор мне удавалось сделать это с помощью 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]; не остается. position, которое можно сохранить в var item, поэтому я получаю консольную ошибку TypeError: item is undefined, насколько я понимаю это.
Я довольно новичок во всем этом, поэтому может быть более простой способ заставить что-то произойти или решить эту ошибку. Большое спасибо за Вашу помощь!