javascript实现的三维正方体(兼容ie7,ff)
通过更新变换矩阵来记录转动(函数remx()).
利用矩阵计算出转动后的正方体顶点坐标,
把各个顶点的空间坐标按”近大远小”转换成平面坐标(函数p2d()),
用正方体各个面的法向量的z坐标判断该面是否可见,
用高为1px的div层模拟画出四边形(函数gra2htm()).
鼠标拖曳的代码用别人的代码修改的.
Cube
function gra2htm(clr,a,b,c,d){
var result='';
var maxx=Math.max(a[0],b[0],c[0],d[0]),minx=Math.min(a[0],b[0],c[0],d[0]);
var maxy=Math.max(a[1],b[1],c[1],d[1]),miny=Math.min(a[1],b[1],c[1],d[1]);
x=new Array(a[0],b[0],c[0],d[0],a[0],b[0],c[0],d[0],a[0],b[0]);
y=new Array(a[1],b[1],c[1],d[1],a[1],b[1],c[1],d[1],a[1],b[1]);
/*/begin
for(var i=0;i
';
}
//end*/
if(maxx-minx>=maxy-miny){
for(var i=3;iy[k-1]){
k--;
xa=(x[k-1]-x[k])/(y[k-1]-y[k]);
}
if(i>y[l+1]){
l++;
xb=(x[l+1]-x[l])/(y[l+1]-y[l]);
}
result+='
';
}
} else {
for(var i=3;ix[k+1]){
k++;
ya=(y[k+1]-y[k])/(x[k+1]-x[k]);
}
if(i>x[l-1]){
l--;
yb=(y[l-1]-y[l])/(x[l-1]-x[l]);
}
result+='
';
}
}
return result;
}
function remx(type,theta,omx){
var sinA=Math.sin(theta),cosA=Math.cos(theta);
var m=new Array();
switch(type){
case 'rx':
m[0]=omx[0];m[1]=omx[1];m[2]=omx[2];
m[3]=omx[3]*cosA-omx[6]*sinA;m[4]=omx[4]*cosA-omx[7]*sinA;m[5]=omx[5]*cosA-omx[8]*sinA;
m[6]=omx[3]*sinA+omx[6]*cosA;m[7]=omx[4]*sinA+omx[7]*cosA;m[8]=omx[5]*sinA+omx[8]*cosA;
break;
case 'ry':
m[0]=omx[0]*cosA-omx[6]*sinA;m[1]=omx[1]*cosA-omx[7]*sinA;m[2]=omx[2]*cosA-omx[8]*sinA;
m[3]=omx[3];m[4]=omx[4];m[5]=omx[5];
m[6]=omx[0]*sinA+omx[6]*cosA;m[7]=omx[1]*sinA+omx[7]*cosA;m[8]=omx[2]*sinA+omx[8]*cosA;
break;
}
return m;
}
function p2d(x,y,z){
var l=100,t=100;
var result=new Array();
result[0]=Math.round(l+x/(z*0.004+1.25));
result[1]=Math.round(t+y/(z*0.004+1.25));
return result;
}
//const
var pa=new Array();
pa[1]=new Array(50,50,-50);
pa[2]=new Array(50,50,50);
pa[3]=new Array(50,-50,50);
pa[4]=new Array(50,-50,-50);
pa[5]=new Array(-50,50,-50);
pa[6]=new Array(-50,50,50);
pa[7]=new Array(-50,-50,50);
pa[8]=new Array(-50,-50,-50);
var idx=new Array();
idx[0]=new Array(1,2,3,4);
idx[1]=new Array(1,4,8,5);
idx[2]=new Array(1,5,6,2);
idx[3]=new Array(7,3,2,6);
idx[4]=new Array(7,8,4,3);
idx[5]=new Array(7,6,5,8);
var clr=new Array('#03c','#c00','#fc0','#f60','#fff','#090');
//end
function cube(id){
if(!document.getElementById(id)) return false;
this.id=document.getElementById(id);
this.angle=new Array();
this.angle2=new Array();
for(i=1;i
var tmr=(new Date()).getTime();
function drag(obj,e){
e=e?e:window.event;
var setx=e.clientX,sety=e.clientY;
if(document.addEventListener){
document.addEventListener('mousemove', inFmove, true);
document.addEventListener('mouseup', inFup, true);
} else if(document.attachEvent){
document.attachEvent('onmousemove', inFmove);
document.attachEvent('onmouseup', inFup);
}
function inFmove(e){
tmr2=(new Date).getTime();
if(tmr2-tmr
var tt,cc=new cube('t');
cc.roll('ry',1);
cc.paint();
[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]