I wanted to create a function which, by each call, creates another rain drop that falls down the screen and gets deleted when at the bottom.
So far I managed to do this with PaperJS, but as soon as I want to delete one rain drop when it hit the bottom, the whole funtion crashes, since it's losing an element in the array [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>
As soon as the first rain drop hits the bottom, it gets removed (as it should) but then as the loop comes to its position again, there is no rainlayer.children[i]; left at this position which can be saved to the var item, so I get the console error TypeError: item is undefined from my understanding of this.
I'm pretty new to all this, so there might been an easier way to make things happen or to solve this error. Thank you very much for your help!
I believe the problem is that you remove all the children from
rainlayer
with the linerainlayer.removeChildren(i)
.You only want the line
item.remove()
- that removes the item from the project so it is no longer in the layer. There is no need to remove children from the layer.rainlayer.removeChildren(from [, to])
is the syntax with an argument so it removes all children from the layer when called with from = 0.