Javascript 和细分,for 循环中浏览器崩溃

Javascript and subdivision, crashing browser in for loop

我正在使用 paper.js 处理一些生成的视觉效果,计划是定义一个随机形状,细分它,然后也随机化这些点(以不同的程度)。现在,浏览器在尝试细分多边形时崩溃。

我对在 Javascript 中做这些事情还比较陌生,所以也许我对它的期望太高了,显然在密集的 for 循环中崩溃是经常发生的事情。有人有一些提示吗?

var Cloud = function(point) {
    this.origin = point;
    this.initBound = new Size(600,200); 
    this.RoM = 40;

    var numsides = 6;
    var scalingFactor = new Point(1,this.initBound.height/this.initBound.width);

    var cloud = new Path.RegularPolygon({
        center: this.origin,
        sides: numsides,
        radius: this.initBound.width/2,
        strokeColor: 'black'
    });

    cloud.scaling = scalingFactor;

    var initBoundBox = new Path.Rectangle({
        point: new Point(point.x-this.initBound.width/2,point.y-this.initBound.height/2),
        size: this.initBound,
        strokeColor: 'red'
    });

    for(var i=0;i<numsides;i++){
        var px = cloud.segments[i].point.x;
        var py = cloud.segments[i].point.y;

        var x = Math.floor(Math.random()*( (px+this.RoM)-(px-this.RoM)+1 ) + (px-this.RoM) );
        var y = Math.floor(Math.random()*( (py+this.RoM)-(py-this.RoM)+1 ) + (py-this.RoM) );

        var tmpP = new Point(x,y);
        cloud.segments[i].point = tmpP;
    }

    for(var i=0;i<cloud.segments.length-1;i++){
        var mdPnt = new Point((cloud.segments[i].point.x+cloud.segments[i+1].point.x)/2,(cloud.segments[i].point.y+cloud.segments[i+1].point.y)/2); 
        cloud.add(i,mdPnt); //breaking here
    }   

    //cloud.smooth();
}

new Cloud(new Point(500,300)); 

在您的最后一个 for 循环中,您在每次迭代中添加一个段,从而将 cloud.segments.length 增加一。你的循环永远不会结束。您可以通过增加 2 而不是 1 或找到更好的二分例程来缓解这种情况。

简而言之,试试这个作为起点:

for(var i=0;i<cloud.segments.length-1;i+=2){
    var mdPnt = new Point((cloud.segments[i].point.x+cloud.segments[i+1].point.x)/2,(cloud.segments[i].point.y+cloud.segments[i+1].point.y)/2); 
    cloud.add(i,mdPnt); //breaking here
}