How to draw 3d object javascript -


i making simple javascript program draws rotated prism. have vectors contain x, y , z coordinates of every point , point connected. problem having cannot find perfect way compare dots in 2d. when figure rotates, has little, still visible, defects , looks lines become longer , shorter. paste important parts of code.

var canvas = document.getelementbyid("canvas-id"); canvas.width = 1200; canvas.height = 500; var ctx = canvas.getcontext("2d"); var dx=[],dy=[],dz=[],dh=[],dgo=[],h=10,ang=10*math.pi/360; var pause=false; for(var i=0;i<h/2;i++){     dx[i]=math.cos(i/h*4*math.pi+math.pi/4)*70.71;     dy[i]=math.sin(i/h*4*math.pi+math.pi/4)*70.71;     console.log(i/h*2*360);     dz[i]=150;     dh[i]=3;     dgo[i]=[];     dgo[i][0]=i+h/2;     dgo[i][1]=i+1;       dgo[i][2]=i-1;      dx[i+h/2]=math.cos(i/h*4*math.pi+math.pi/4)*70.71;     dy[i+h/2]=math.sin(i/h*4*math.pi+math.pi/4)*70.71;     dz[i+h/2]=250;     dh[i+h/2]=3;     dgo[i+h/2]=[];     dgo[i+h/2][0]=i;     dgo[i+h/2][1]=i+h/2+1;     dgo[i+h/2][2]=i+h/2-1;     if(i==h/2-1){         dgo[i][1]-=h/2;         dgo[i+h/2][1]-=h/2;     }     if(i==0){         dgo[i][2]+=h/2;         dgo[i+h/2][2]+=h/2;     } } window.addeventlistener("mouseup", function (args) {         pause=!pause; }, false); function abs(a){     if(a>=0) return a;     return -a; } function pit(x1,y1,x2,y2){     return math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } function rotate(x,y,z){     for(var i=0;i<h;i++){         var m=math.atan2(dx[i]-x,dz[i]-z)/2/math.pi*360-90,dis=pit(dx[i],dz[i],x,z);         if(m>0) m-=360         dx[i]=x+math.cos(abs(m)/360*2*math.pi+ang)*dis;         dz[i]=z+math.sin(abs(m)/360*2*math.pi+ang)*dis;     } } function update() {     if(!pause)rotate(0,0,200)     settimeout(update, 10); } function line(x1,y1,x2,y2){     if((x1>0 && y1>0 && x1<canvas.width && y1<canvas.height) || (x2>0 && y2>0 && x2<canvas.width && y2<canvas.height))     ctx.beginpath();     ctx.moveto(x1,y1);     ctx.lineto(x2,y2);     ctx.stroke();     ctx.closepath(); } function draw() {     ctx.clearrect(0, 0, canvas.width, canvas.height);     ctx.globalalpha = 1;     for(var i=0;i<h;i++){         for(var j=0;j<dh[i];j++){             if(dz[i]>0 && dz[dgo[i][j]]>0)                 line(dx[i]/math.sqrt(dz[i])*10+canvas.width/2,dy[i]/math.sqrt(dz[i])*10+canvas.height/2,                      dx[dgo[i][j]]/math.sqrt(dz[dgo[i][j]])*10+canvas.width/2,dy[dgo[i][j]]/math.sqrt(dz[dgo[i][j]])*10+canvas.height/2);         }     } console.log(ctx.translate(0,0,10));     requestanimationframe(draw); } draw();  update(); 


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -