我正在使用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));
答案 0 :(得分:2)
在你的上一个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
}