我想创建一个函数,通过每次调用,创建另一个降落在屏幕上的雨滴,并在底部被删除。
到目前为止,我设法用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>
&#13;
一旦第一次降雨击中底部,它就会被移除(应该如此),但随着环路再次到达它的位置,就没有 rainlayer.children [i]; 离开这个位置可以保存到var 项目,所以我得到了控制台错误 TypeError:item is undefined 来自我对此的理解。
我对这一切都很陌生,所以可能有一种更简单的方法可以让事情发生或解决这个错误。非常感谢你的帮助!
答案 0 :(得分:1)
我认为问题是您使用第rainlayer
行删除rainlayer.removeChildren(i)
中的所有子女。
您只需要行item.remove()
- 从项目中删除项目,使其不再位于图层中。无需从图层中删除子项。
rainlayer.removeChildren(from [, to])
是带有参数的语法,因此当从= 0调用时,它会从图层中删除所有子项。