I'm working on some generative visuals using paper.js, and the plan is to define a random shape, subdivide it, and then randomize those points as well (to a different degree). Right now, the browser is crashing while attempting to subdivide a polygon.
I'm relatively new to doing these things in Javascript, so maybe I am expecting too much out of it, apparently crashes within intensive for loops are just something that happen. Does anyone have some tips?
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));
In your last for-loop, you're adding a segment in each iteration, and thereby increasing cloud.segments.length by one. Your loop never ends. You can mitigate this by incrementing by 2 instead of 1, or finding a better bisection routine.
In short, try this as a starting point:
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.