Scalable Polygon Grid Using For Loop
I want to create an interactive digital canvas that will generate a series of near-square polygons in a grid. The below jsFiddle shows a 2x2 grid system of said polygons. If you in
Solution 1:
How to draw a grid with slightly random offset intersection points
Think of each intersecting point on your grid as a circle’s centerpoint.
Then you can calculate an offset from that centerpoint using a random radius and a random angle.
This will randomly offset each intersecting point.
Here’s an example of how to calculate gridpoints with a 0-2.5 pixel “wobble” off it's "usual" position:
// make each grid cell's side 20px // (you can alter this to fit your needs)var sideLength=20;
// allow the point to wobble up to 2.5 pixels from its "usual" positionvar radius=2.5*Math.random();
// allow that point to wobble at a random angle around its "usual" positionvar radianAngle=2*Math.PI*Math.random();
// do the calculation of the new wobbled intersection point// the x & y are the cell's horizontal(x) and vertical(y) position on the gridvar cx=x*sideLength+radius*Math.cos(radianAngle);
var cy=y*sideLength+radius*Math.sin(radianAngle);
Here is example code and a Fiddle: http://jsfiddle.net/m1erickson/Wqhb9/
<!doctype html><html><head><linktype="text/css"media="all"href="css/reset.css" /><!-- reset css --><scripttype="text/javascript"src="http://code.jquery.com/jquery.min.js"></script><style>body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style><script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// declare an arrayvar points=newArray(17);
for(var i=0;i<points.length;i++){
points[i]=newArray(17);
}
var sideLength=20;
// fill the array with for(var y=0;y<17;y++){
for(var x=0;x<17;x++){
// create a random semi-offset grid pointvar radius=2.5*Math.random();
var radianAngle=2*Math.PI*Math.random();
var cx=x*sideLength+radius*Math.cos(radianAngle);
var cy=y*sideLength+radius*Math.sin(radianAngle);
// if this is a sidepoint, don't offset (sides are straight)if(x==0){cx=0;}
if(y==0){cy=0;}
if(x==16){cx=x*sideLength;}
if(y==16){cy=y*sideLength;}
// add this gridpoint to the points array
points[x][y]={x:cx+10,y:cy+10};
}
}
// stroke the 4 sides of each cellfor(var y=0;y<16;y++){
for(var x=0;x<16;x++){
strokeCell(x,y);
}
}
// draw the 4 sides of the cellfunctionstrokeCell(x,y){
var pt0=points[x][y];
var pt1=points[x+1][y];
var pt2=points[x+1][y+1];
var pt3=points[x][y+1];
ctx.beginPath();
ctx.moveTo(pt0.x,pt0.y);
ctx.lineTo(pt1.x,pt1.y);
ctx.lineTo(pt2.x,pt2.y);
ctx.lineTo(pt3.x,pt3.y);
ctx.closePath();
ctx.stroke();
}
}); // end $(function(){});</script></head><body><canvasid="canvas"width=400height=400></canvas></body></html>
Post a Comment for "Scalable Polygon Grid Using For Loop"